AcWing 756. 蛇形矩阵
原题链接
简单
作者:
回归线
,
2021-03-28 08:42:30
,
所有人可见
,
阅读 274
#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
bool flag[N][N];
int main() {
int n, m, p, q;
cin >> n >> m;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int x = 0, y = 0, d = 0;
for (int i = 0; i< m * n; ++i) {
a[x][y] = i + 1;
flag[x][y] = true;
p = x + dx[d];
q = y + dy[d];
if (p<0 || p >=n || q<0 || q>=m || flag[p][q]) {
d = (d + 1) % 4;
p = x + dx[d];
q = y + dy[d];
}
x = p;
y = q;
}
for (int i = 0; i < n; ++i) {
for (int j= 0; j < m; ++j) {
cout << a[i][j] << ' ';
}
cout << endl;
}
return 0;
}