#include<stdio.h> #include<string.h> int a[110][110]; int main() { int n; int i,j; while(~scanf("%d",&n)){ memset(a,0,sizeof(a)); int s=1; i=0; j=n-1; a[0][n-1]=1; while(s<n*n){ while(i+1<n && !a[i+1][j]) a[++i][j]=++s; while(j-1>=0 && !a[i][j-1]) a[i][--j]=++s; while(i-1>=0 && !a[i-1][j]) a[--i][j]=++s; while(j+1<n && !a[i][j+1]) a[i][++j]=++s; } for(i=0;i<n;i++){ for(j=0;j<n;j++){ printf("%d ",a[i][j]); } printf("\n"); } } return 0; }
3
7 8 1
6 9 2
5 4 3
从右上角开始,优先向下走,走到头再往左走,接着往上走,走到头往右走,控制好界限皆可
#include<stdio.h> #include<string.h> int a[110][110]; int main() { int n; int i,j; while(~scanf("%d",&n)){ memset(a,0,sizeof(a)); int s=1; i=0; j=n-1; a[0][n-1]=1; while(s<n*n){ while(i+1<n && !a[i+1][j]) a[++i][j]=++s; while(j-1>=0 && !a[i][j-1]) a[i][--j]=++s; while(i-1>=0 && !a[i-1][j]) a[--i][j]=++s; while(j+1<n && !a[i][j+1]) a[i][++j]=++s; } for(i=0;i<n;i++){ for(j=0;j<n;j++){ printf("%d ",a[i][j]); } printf("\n"); } } return 0; }