//为什么我保存了后按CT + F5,不重新编译直接执行了?搞得我还以为出bug了..
#include <iostream>
#include <cstdio>
using namespace std;
#define MAXN 20
int arr[MAXN][MAXN];
int main(void) {
int n;
while (cin >> n) {
int col = n - 1;//row :行
int row = 0;//col : 列
int num = 1;
memset(arr, 0, sizeof(arr));
arr[row][col] = num;
while (num < n * n) {
//&&是短路运算符哦,所以不会有越界问题的发生
while (row + 1 < n && !arr[row + 1][col])
arr[++row][col] = ++num;
while (col > 0 && !arr[row][col - 1])
arr[row][--col] = ++num;
while (row > 0 && !arr[row - 1][col])
arr[--row][col] = ++num;
while (col + 1 < n && !arr[row][col + 1])
arr[row][++col] = ++num;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j] << "\t";
cout << endl;
}
cout << endl;
}
}
填数的顺序是下,左,上,右,在遇到非零数或是到边界时改变方向。
需要注意的是,二维数组的存储更像是矩阵而不是坐标系,所以我用row和col来表示坐标。