AcWing 756. 蛇形矩阵
原题链接
简单
作者:
自豪的澡巾QAQ
,
2021-02-15 13:44:10
,
所有人可见
,
阅读 285
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 110;
int main() {
int n,m;
cin >> n >> m;
int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
int ans[N][N],dir = 1,x = 1,y = 1;
for (int i = 1;i <= n * m;i++) {
int next_x = x + dx[dir],next_y = y + dy[dir];
if (next_x > n || next_y > m || next_x < 1 || next_y < 1 || ans[next_x][next_y] > 0)
dir = (dir + 1) % 4;
ans[x][y] = i;
x += dx[dir];
y += dy[dir];
}
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= m;j++) {
cout << ans[i][j] << ' ';
}
cout << endl;
}
}