AcWing 756. 蛇形矩阵
原题链接
简单
作者:
wjie
,
2021-01-11 12:17:17
,
所有人可见
,
阅读 351
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 105;
int arr[N][N], n, m;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void dfs(int x, int y, int color, int dir)
{
if (color > n * m) return;
arr[x][y] = color;
int nx = x + dx[dir], ny = y + dy[dir];
if (nx < 0 || nx >= n || ny < 0 || ny >= m || arr[nx][ny])
{
dir = (dir + 1) % 4;
nx = x + dx[dir], ny = y + dy[dir];
}
dfs(nx, ny, color+1, dir);
}
int main()
{
scanf("%d%d", &n, &m);
dfs(0, 0, 1, 0);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
printf("%d ", arr[i][j]);
}
puts("");
}
return 0;
}