`
mywebcode
  • 浏览: 1002798 次
文章分类
社区版块
存档分类
最新评论

蛇形填数

 
阅读更多

描述在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
916 13 2
815 14 3
76 5 4

#include<stdio.h>
#include<string.h>
#define MAX 10
int a[MAX][MAX];
int main()
{
int n,x,y,tot=0;
scanf("%d",&n);
memset(a,0,sizeof(a));
tot=a[x=0][y=n-1]=1;
while(tot<n*n)
{
while(x+1<n && !a[x+1][y]) a[++x][y]=++tot;
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;
}
for(x=0;x<n;x++)
{
for(y=0;y<n;y++)
printf("%3d",a[x][y]);
printf("\n");
}
return 0;
}
//运行结果

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics