在 n×n 方陣中按蛇形填入 1 到 n²。n=4 時:
10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
規律:右→左→下→左→上→右→... 循環。
#include#include int a[10][10]; int main() { int n, count, i, j; memset(a, 0, sizeof(a)); scanf("%d", &n); // 起始位置:第1行第n列 i = 1; j = n; count = a[i][j] = 1; while (count < n*n) { // 向下 while (i < n && a[i+1][j] == 0) a[++i][j] = ++count; // 向左 while (j > 1 && a[i][j-1] == 0) a[i][--j] = ++count; // 向上 while (i > 1 && a[i-1][j] == 0) a[--i][j] = ++count; // 向右 while (j < n && a[i][j+1] == 0) a[i][++j] = ++count; } // 輸出 for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) printf("%3d%c", a[i][j], j==n?'\n':' '); } return 0; }
輸入: 4 輸出: 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
dx[4]={1,0,-1,0}, dy[4]={0,-1,0,1} 簡化代碼?