AcWing 756. 蛇形矩阵
原题链接
简单
作者:
强者
,
2025-02-02 15:55:31
,
所有人可见
,
阅读 1
#include <stdio.h>
int main() {
int n, m;
scanf("%d %d", &n, &m);
int matrix[n][m];
int visited[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
visited[i][j] = 0;
}
}
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int direction = 0;
int x = 0, y = 0;
for (int num = 1; num <= n * m; num++) {
matrix[x][y] = num;
visited[x][y] = 1;
int nx = x + dx[direction];
int ny = y + dy[direction];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny]) {
x = nx;
y = ny;
} else {
direction = (direction + 1) % 4;
x = x + dx[direction];
y = y + dy[direction];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d", matrix[i][j]);
if (j < m - 1) printf(" ");
}
printf("\n");
}
return 0;
}