AcWing 756. 蛇形矩阵
原题链接
简单
作者:
SayYong
,
2024-10-07 08:41:11
,
所有人可见
,
阅读 1
#include <iostream>
using namespace std;
const int N = 110;
int matrix[N][N];
int main(void)
{
int n, m;
cin >> n >> m;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int d = 0;
int x = 0, y = 0;
for (int i = 1; i <= n * m; i++) {
int a = x + dx[d], b = y + dy[d];
matrix[x][y] = i;
// cout << i << endl;
if (a < 0 || a >= n || b < 0 || b >= m || matrix[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << matrix[i][j] << ' ';
}
cout << endl;
}
}