小弟写的蛇形填数程序,大神来完善一下吧
/*我说的蛇形数指这样的矩阵(n<10): 7 8 16 9 2
5 4 3 (n=3)
我的算法是先写一个10*10矩阵,每个元素都置零,然后循环判断(只判断从a[1][1]到a[n][n])按制定规则处理,直到标志数flag不为零时结束。我的flag是int时,当n<=5时正确,但当n>=6时是死循环,flag总是0.(这里我不明白为什么,我猜是flag溢出???)后来我把flag改成double就对了。有没有保持flag是int 的别的巧妙的办法呢?*/
//蛇形填数
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main()
{
int n,i,j,k,l;
double flag=0;
int a[10][10];
scanf("%d",&n);
for(i=0;i<10;i++)
for(j=0;j<10;j++)
a[i][j]=0;
a[1][n]=1;
while((flag-0)<=0.00001)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if((a[i][j]>0)&&(a[i+1][j]==0)&&(a[i][j+1]==0)&&(a[i-1][j]==0)&&(a[i][j-1]==0))
a[i+1][j]=a[i][j]+1;//1.第一个元素的处理
else if((a[i][j]>0)&&(a[i][j-1]==a[i][j]-1)&&(a[i+1][j]==0)&&(a[i+2][j]==0)&&(a[i][j+1]==0))
a[i][j+1]=a[i][j]+1;//下边两个零时向右增加,如n=6时23到24
else if((a[i][j]>0)&&(a[i][j+1]==a[i][j]+1)&&(a[i+1][j]==0))
;
else if((a[i][j]>0)&&(a[i-1][j]>0)&&(a[i+1][j]==0)&&(i!=j))
a[i+1][j]=a[i][j]+1;//2.
else if((a[i][j]>0)&&(a[i-1][j]>0)&&(a[i][j-1]==0)&&(i==j))
a[i][j-1]=a[i][j]+1;//3
else if((a[i][j]>0)&&(a[i][j+1]==a[i][j]-1)&&(a[i][j-1]==0)&&((i+j)!=(n+1)))
a[i][j-1]=a[i][j]+1;//4.要补充:&&(a[i+1][j]!=a[i][j]+1)?
else if((a[i][j]>0)&&(a[i][j]==a[i][j+1]+1)&&(a[i-1][j]==0)&&(i+j==(n+1)))
a[i-1][j]=a[i][j]+1;//5.
else if((a[i][j]>0)&&(a[i+1][j]==a[i][j]-1)&&(a[i-1][j]==0)&&(i!=j))
a[i-1][j]=a[i][j]+1;//6
else if((a[i][j]>0)&&(a[i+1][j]==a[i][j]-1)&&(a[i][j+1]==0)&&(i==j))
a[i][j+1]=a[i][j]+1;//7
else if((a[i][j]>0)&&(a[i][j-1]==a[i][j]-1)&&(a[i][j+1]==0)&&(i+j!=n))
a[i][j+1]=a[i][j]+1;//8
else if((a[i][j]>0)&&(a[i][j]==a[i][j-1]+1)&&(a[i+1][j]==0)&&(i+j==n))
a[i+1][j]=a[i][j]+1;//9
else
;
else if((a[i][j]>0)&&(a[i][j+1]>0)&&(a[i][j-1]==0)&&((i+j)!=(n+1))&&(a[i+1][j]==a[i][j]+1))
;//ÌØÊâ2*/
flag=1.0;
for(k=1;k<=n;k++)
{
for(l=1;l<=n;l++)
{
printf("%-3d ",a[k][l]);
flag=(flag*a[k][l]);
}
printf ("\n");
}
printf ("\n");
printf("%lf\n",flag);
}
}
printf("consequence:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%-3d ",a[i][j]);
printf ("\n");
}
return 0;
}
[ 本帖最后由 qq770903321 于 2013-1-26 21:13 编辑 ]