codevs1160 蛇形矩阵
题目描述 Description
小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字,请输出该n行n列正方形矩阵以及其的对角线数字之和.
输入描述 Input Description
n(即n行n列)
输出描述 Output Description
n+1行,n行为组成的矩阵,最后一行为对角线数字之和
样例输入 Sample Input
3
样例输出 Sample Output
5 4 3
6 1 2
7 8 9
25
#include <stdio.h>
#include <string.h>
int main(){
int a[110][110];
int n,x,y,tot,num=0;
scanf("%d",&n);
memset(a,0,sizeof(a));
tot=n*n;
a[x=n-1][y=n]=n*n;
while(tot>0){
while(y-1>=0 && !a[x][y-1]) a[x][--y]=--tot;
while(x-1>=0 && !a[x-1][y]) a[--x][y]=--tot;
while(y+1<n && !a[x][y+1]) a[x][++y]=--tot;
while(x+1<n && !a[x+1][y]) a[++x][y]=--tot;
}
for(x=0;x<n;x++){
for(y=0;y<n;y++)printf("%d ",a[x][y]+1);
printf("\n");
}
for(x=0;x<n;x++)
for(y=0;y<n;y++){
if(x==y || x+y==n-1)num+=a[x][y]+1;
}
printf("%d\n",num);
return 0;
}

浙公网安备 33010602011771号