题目描述
蛇形矩阵
样例
#include<bits/stdc++.h>
using namespace std;
const int N = 110;
int arr[N][N];
int n, m;
int dx[4] = {1, 0, -1, 0}; // 下, 左, 上, 右
int dy[4] = {0, -1, 0, 1};
int main() {
cin >> n >> m;
int x = 1, y = 1;
int t = 3;
for (int i = 1; i <= n * m; i ++ ) {
arr[x][y] = i;
int a = x + dx[t];
int b = y + dy[t];
if (a < 1 || a > n || b < 1 || b > m || arr[a][b] != 0) {
t ++ ;
t %= 4;
a = x + dx[t];
b = y + dy[t];
}
x = a;
y = b;
}
for (int i = 1; i <= n; i ++ ) {
for (int j = 1; j <= m; j ++ ) {
cout << arr[i][j] << ' ';
}
cout << '\n';
}
return 0;
}
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla