//蛇形填数 //10 11 12 1 //9 16 13 2 //8 15 14 3 //7 6 5 4 #include#include //setw(5)调用 #define MAXN 10//最大为10*10数组 using namespace std; int a[MAXN][MAXN]; int main() { int t = 0, n, x, y; cin >> n;//n维数组 memset(a, 0, sizeof(a));//初始化数组为0 t = a[x = 0][y = n - 1] = 1; while (t < n * n) { while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++t;//下 while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++t;//左 while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++t;//上 while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++t;//右 } for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) { cout << setw(5) << a[i][j]; }cout << endl; } return 0; }
输入:5
输出:
13 14 15 16 1
12 23 24 17 2
11 22 25 18 3
10 21 20 19 4
9 8 7 6 5



