#include<iostream> #include<vector> #include<algorithm> #define max 20 using namespace std; int a[max][max]; int main() { int x, y, n, tot = 0; cin >> n; memset(a, 0, sizeof(a)); tot = a[x = 0][y = n - 1] = 1; while (tot<n*n) { while (x + 1 < n&&!a[x + 1][y]) a[++x][y] = ++tot; while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++tot; while (x - 1>=0 && !a[x - 1][y])a[--x][y] = ++tot; while (y + 1 < n&&!a[x][y + 1]) a[x][++y] = ++tot; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << a[i][j] << " "; } cout << endl; } system("pause"); return 0; }
来源:https://www.cnblogs.com/wujufengyun/p/6897245.html