蛇形矩阵
#include<cstdio> #include<cstring> using namespace std; int main() { int n; int a[11][11]; while(~scanf("%d",&n)){ memset(a,0,sizeof(a)); int tot = 1; int x,y; a[0][0] = 1; x = 0;y = 0; while(tot < n*n){ while(y < n - 1 && !a[x][y+1]) a[x][++y] = ++tot; while(x < n - 1 && !a[x+1][y]) a[++x][y] = ++tot; while(y >= 1 && !a[x][y-1]) a[x][--y] = ++tot; while(x >= 1 && !a[x-1][y]) a[--x][y] = ++tot; } if(n <= 3 ){ for(x = 0 ; x < n ; x++){ for(y = 0 ; y < n;y++){ printf("%d ",a[x][y]); } printf("\n"); } } else if(n >= 4 && n <= 9){ for(x = 0 ; x < n ; x++){ for(y = 0 ; y < n ; y++) printf("%2d ",a[x][y]); printf("\n"); } } else { for(x = 0 ; x < n ; x++){ for(y = 0 ; y < n ; y++){ if( x == 5 && y == 3) printf("%2d ",a[x][y]); else printf("%2d ",a[x][y]); } printf("\n"); } } } return 0; }