蛇形矩阵
题目参考<算法竞赛入门经典>第二版第三章 3.1
1 #include <stdio.h> 2 #include <string.h> 3 4 #define N 20 5 int a[N][N]; 6 int main(int argc, char **argv){ 7 int n; 8 while(scanf("%d",&n)!=EOF){ 9 memset(a, 0, sizeof(a)); 10 int tol = 1; 11 int x, y; 12 x = -1; 13 y = n; 14 while(tol<=n*n){ 15 x++; 16 y--; 17 while( x < n && a[x][y] == 0){ 18 a[x++][y] = tol++; 19 }// x = n y = n-1 20 x--; 21 y--; 22 while(y >= 0 && a[x][y] == 0){ 23 a[x][y--] = tol++; 24 } 25 x--; 26 y++; 27 while(x >= 0 && a[x][y] == 0){ 28 a[x--][y] = tol++; 29 } 30 x++; 31 y++; 32 while( y < n && a[x][y] == 0){ 33 a[x][y++] = tol++; 34 } 35 } 36 for(int i=0; i<n;i++){ 37 for(int j=0;j<n;j++){ 38 printf("%3d ",a[i][j]); 39 } 40 printf("\n"); 41 } 42 } 43 return 0; 44 }