这道题还是和蛇形填数有关,因为要不停的去转圈圈去判断是否到了最中间的那个位置,所以用到了递归的思想。
#include<stdio.h>
int n,a[100][100];
void rewrite(int n,int count,int END)
{
int i;
for(i=n-END-1;i>END;i--)
a[n-END-1][i]=count--;
if(!(count-1)){a[n/2][n/2]=1;return;}
for(i=n-END-1;i>END;i--)
a[i][END]=count--;
for(i=END;i<n-END-1;i++)
a[END][i]=count--;
for(i=END;i<n-END-1;i++)
a[i][n-END-1]=count--;
rewrite(n,count,END+1);
}
int main(){
int i,j;
int sum = 0;
scanf("%d",&n);
rewrite(n,n*n,0);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("%d%c",a[i][j],j==n-1?'
':' ');
if(i==j||i+j == n-1) sum += a[i][j];
}
printf("%d
",sum);
return 0;
}