算法竞赛入门经典 例题 3-2 蛇形填数
在n*n方阵里填入1,2,„,n*n。要求填成蛇形。比如n=4时方阵为
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
上面的方阵中。多余的空格仅仅是为了便于观察规律,不必严格输出。n≤8。
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 10 int a[MAXN][MAXN]; int main(int argc, char *argv[]) { int n, count = 1; int x, y; scanf("%d", &n); memset(a, 0, sizeof(a)); x = 0; y = n-1; a[x][y] = 1; while(count < n*n) { while(x+1<n && !a[x+1][y]) a[++x][y] = ++count; //a[x++][y] 细节决定成败,这种话x就变了 while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++count; while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++count; while(y+1<n && !a[x][y+1]) a[x][++y] = ++count; } for(x = 0; x < n; x++) { for(y = 0; y < n; y++) printf("%3d", a[x][y]); printf("\n"); } /* while(count <= n*n) { while(x < n-1 && !a[x][y]) {a[x][y] = count; x++; count++;} while(y > 0 && !a[x][y]) {a[x][y] = count; y--; count++; } while(x > 0 && !a[x][y]) {a[x][y] = count; x--; count++; } while(y < n-1 && !a[x][y]) {a[x][y] = count; y++; count++; } } for(x = 0; x <= n-1; x++) { for(y = 0; y< n-1; y++) printf("%d ", a[x][y]); printf("%d\n", a[x][y]); } */ system("PAUSE"); return 0; }
总结:1 推断是否越界和推断是否填过数字
2 边界条件,>还是>=等,先推断,后x,y才变化
3 x++里x也变化,要牢记
4 a[0][3]一開始就赋值了