【题目】方阵填数:在一个N×N的方阵中,填入1,2,.....N×N个数,并要求
构成如下的格式:
如 N=4 N=5
10 11 12 1 13 14 15 16 1
9 16 13 2 12 23 24 17 2
8 15 14 3 11 22 25 18 3
7 6 5 4 10 21 20 19 4
9 8 7 6 5
请用WIN-TC或C遍一个程序把方阵给编出来。
[此贴子已经被作者于2004-08-05 12:09:07编辑过]
我编了出来,但就是有问题,能给小弟指明指明吗?
#include "stdio.h" #define N 100 main() {int i,j,k,s,j1,j2,j3,j4,a[N][N],n; printf("please imput a number:"); scanf("%d",&n); if(n%2==1){k=(n+1)/2;a[k][k]=1 for(s=1;s<=k-1;s++) a[k-s][k+s]=(1+2*s)*(1+2*s); {for(j1=1;j1<=2*s;j1++) a[k-s+j1][k+s]=a[k-s][k+s]-j1; for(j2=1;j2<=2*s;j2++) a[k-s+j1][k+s-j2]=a[k-s+j1][k+s]-j2; for(j3=1;j3<=2*s;j3++) a[k-s+j1-j3][k+s-j2]=a[k-s+j1][k+s-j2]-j3; for(j4=1;j4<=2*s-1;j4++) a[k-s+j1-j3][k+s-j2+j4]=a[k-s+j1-j3][k+s-j2]-j4; } } else{k=n/2; a[k][k+1]=4; for(s=1;s<=k-1;s++) {a[k-s][k+s]=(2+2*s)*(2+2*s); for(j1=1;j1<=2*s-1;j1++) a[k-s+j1][k+s]=a[k-s][k+s]-j1; for(j2=1;j2<=2*s-1;j2++) a[k-s+j1][k+s-j2]=a[k-s+j1][k+s]-j2; for(j3=1;j3<=2*s-1;j3++) a[k-s+j1-j3][k+s-j2]=a[k-s+j1][k+s-j2]-j3; for(j4=1;j4<=2*s-2;j4++) a[k-s+j1-j3][k+s-j2+j4]=a[k-s+j1-j3][k+s-j2]-j4; } } for(i=1;i<=n;i++) {for(j=1;j<=n;j++) printf("%3d ",a[i][j]); printf("\n\n"); } getch(); }
不好意思,上面的的确有问题,正确的答案在这里:
#include "stdio.h" #define N 100 main() {int i,j,k,s,j1,j2,j3,j4,a[N][N],n; printf("please imput a number:"); scanf("%d",&n); if(n%2==1){k=(n+1)/2;a[k][k]=1; for(s=1;s<=k-1;s++) {a[k-s][k+s]=(1+2*s)*(1+2*s); for(j1=1;j1<=2*s;j1++) a[k-s+j1][k+s]=a[k-s][k+s]-j1; for(j2=1;j2<=2*s;j2++) a[k+s][k+s-j2]=a[k+s][k+s]-j2; for(j3=1;j3<=2*s;j3++) a[k+s-j3][k-s]=a[k+s][k-s]-j3; for(j4=1;j4<=2*s-1;j4++) a[k-s][k-s+j4]=a[k-s][k-s]-j4; } } else{k=n/2; for(s=1;s<=k;s++) {a[k-s+1][k+s]=4*s*s; for(j1=1;j1<=2*s-1;j1++) a[k-s+1+j1][k+s]=a[k-s+1][k+s]-j1; for(j2=1;j2<=2*s-1;j2++) a[k+s][k+s-j2]=a[k+s][k+s]-j2; for(j3=1;j3<=2*s-1;j3++) a[k+s-j3][k-s+1]=a[k+s][k-s+1]-j3; for(j4=1;j4<=2*s-2;j4++) 4a[k-s+1][k-s+1+j4]=a[k-s+1][k-s+1]-j4; } } for(i=1;i<=n;i++) {for(j=1;j<=n;j++) printf("%3d ",a[i][j]); printf("\n\n"); } getch(); } 若有更简单的方法,请不烦传上来。谢了。