AcWing 756. 蛇形矩阵
原题链接
简单
作者:
Value
,
2021-03-01 20:15:09
,
所有人可见
,
阅读 248
#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
int main(){
int n, m; cin >> n >> m;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int x = 0, y = 0, d = 1;
for(int i = 1; i <= n * m; i ++ ){
a[x][y] = i;
int xx = x + dx[d];
int yy = y + dy[d];
if(xx < 0 || yy < 0 || xx >= n || yy >= m || a[xx][yy]){
d = (d + 1) % 4;
xx = x + dx[d], yy = y + dy[d];
}
x = xx, y = yy;
}
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < m; j ++ ){
cout << a[i][j] << ' ';
}
cout << endl;
}
return 0;
}