您的位置:首页 > 其它

算法之路二:刘汝佳算法竞赛入门经典 3.3蛇形填数

2017-01-23 14:19 316 查看
#include<stdio.h>
#include<string.h>
#define maxn 20
int a[maxn][maxn];
int main()
{
int n,x,y,tot=0;//行x,列y
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法
相关文章推荐