模拟填数的过程
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
void snake(int n) {
int t = 1, tot = n*n;
int a[n][n]; //存储数据的二维数组
int i = 0,j = n-1; //两个动态变换的坐标,记录行走过程中的位置
memset(a, 0, sizeof(a)); //二维数组不能直接赋值 a[n][n] = {0} 无效!!
a[i][j] = t++;
while (t <= tot) {
while (i+1 < n && a[i+1][j] == 0) a[++i][j] = t++; //向下走
while (j-1 >= 0 && a[i][j-1] == 0) a[i][--j] = t++; //向左走
while (i-1 >= 0 && a[i-1][j] == 0) a[--i][j] = t++; //向上走
while (j+1 < n && a[i][j+1] == 0) a[i][++j] = t++; //向右走
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
int main() {
int n;
scanf("%d", &n);
snake(n);
return 0;
}