被初始化的全局变量:棋盘、可能马可以走到的点的坐标
自定义函数:nextpos、movenext
主函数功能:
#include
#include
int move1[8]={2,2,1,1,-1,-1,-2,-2,},
move2[8]={1,-1,2,-2,2,-2,1,-1,},
board[8][8]={{0}};
int nexti[8],nextj[8],npos,cur_row,cur_col,step,outwrite=1;
/*函数nextpos计算位置(i,j)出口个数*/
int nextpos(int i,int j,int a[8],int b[8])
{
int count=0,k,i1,j1;
for(k=0;k<8;k++){
i1=i+move1[k];
j1=j+move2[k];
if(i1>7||i1<0||j1>7||j1<0)
continue;
else if(board[i1][j1]!=0)
continue;
else{
a[count]=move1[k];
b[count]=move2[k];
++count;
printf("i is %d\n",a[count]);
printf("j is %d\n",b[count]);
}
}
return(count);
}
/*函数movenext在有多出口时,选择适当出口推进一步*/
int movenext(int *i,int *j,int a[],int b[])
{
int temp,count=8,a1[8],b1[8],
nexti_like[8],nextj_like[8],
cur_row_like,cur_col_like,k,t;
for(k=0;k<npos;k++)
{
temp=nextpos(*i+nexti[k],*j+nextj[k],a1,b1);
if(temp<count)
{
cur_row_like=*i+nexti[k];
cur_col_like=*j+nextj[k];
count=temp;
for(t=0;t<count;t++)
{
nexti_like[t]=a1[t];
nextj_like[t]=b1[t];
}
}
}
*i=cur_row_like;
*j=cur_col_like;
for(k=0;k<count;k++)
{
a[k]=nexti_like[k];
b[k]=nextj_like[k];
}
return count;
}
int main()
{
int i,j;
printf("\nEnter the starting position(row,col):");
scanf("%d",&cur_row);/*输入起始位置*/
scanf("%d",&cur_col);
board[cur_row][cur_col]=1;
npos=nextpos(cur_row,cur_col,nexti,nextj);
printf("nexti is %d",nexti[0]);
printf("出口数量为 %d",npos);
for(step=2;step<=64;step++)
{
if(npos==0){
outwrite=0;
break;
}
else if(npos==1){
cur_row+=nexti[0];
cur_col+=nextj[0];
board[cur_row][cur_col]=step;
npos=nextpos(cur_row,cur_col,nexti,nextj);
}
else{
npos=movenext(&cur_row,&cur_col,nexti,nextj);
board[cur_row][cur_col]=step;
}
}
if(outwrite==0)
printf("\n no solution\n");
else{
printf("\n A solution:\n");
for(i=0;i<8;i++){
for(j=0;j<8;j++)
printf("%4d",board[i][j]);
printf("\n");
}
}
printf("%d",board[5][6]);
system("pause");
}