|

楼主 |
发表于 2020-3-22 21:48:40
|
显示全部楼层
用深度优先打印出棋子的所有落脚点顺序
#include <stdio.h>
#include <stdlib.h>
#define X 8
#define Y 8
int chess[X][Y];
// 找到基于(x,y)位置的下一个可走的位置
int next(int *px, int *py, int count)
{
int x=*px, y=*py;
switch(count) //棋子可能的8种落脚点
{
case 0:
if(x-2>=0&&y-1>=0&&chess[x-2][y-1]==0)
{
*px=x-2;
*py=y-1;
return 1;
}
break;
case 1:
if(x-2>=0&&y+1<Y&&chess[x-2][y+1]==0)
{
*px=x-2;
*py=y+1;
return 1;
}
break;
case 2:
if(x+2<X&&y-1>=0&&chess[x+2][y-1]==0)
{
*px=x+2;
*py=y-1;
return 1;
}
break;
case 3:
if(x+2<X&&y+1<Y&&chess[x+2][y+1]==0)
{
*px=x+2;
*py=y+1;
return 1;
}
break;
case 4:
if(x-1>=0&&y-2>=0&&chess[x-1][y-2]==0)
{
*px=x-1;
*py=y-2;
return 1;
}
break;
case 5:
if(x-1>=0&&y+2<Y&&chess[x-1][y+2]==0)
{
*px=x-1;
*py=y+2;
return 1;
}
break;
case 6:
if(x+1<X&&y-2>=0&&chess[x+1][y-2]==0)
{
*px=x+1;
*py=y-2;
return 1;
}
break;
case 7:
if(x+1<X&&y+2<Y&&chess[x+1][y+2]==0)
{
*px=x+1;
*py=y+2;
return 1;
}
break;
default:
break;
}
return 0;
}
// 深度优先遍历棋盘
// (x,y)为位置坐标
// tag是标记变量,每走一步,tag+1
//用回溯法
int sethorse(int x, int y,int tag)
{
int x1=x,y1=y,flag=0,count=0;
chess[x][y]=tag;
// 如果tag==X*Y,则完成整个棋盘的遍历
if(tag==X*Y)
{
return 1;
}
flag = next(&x1,&y1,count);
while(flag==0&&count<7)
{
count++;
flag = next(&x1,&y1,count);
}
while(flag)
{
if(sethorse(x1,y1,tag+1))
{
return 1;
}
x1=x;
y1=y;
count++;
flag = next(&x1,&y1,count);
while(flag==0&&count<7)
{
count++;
flag = next(&x1,&y1,count);
}
}
if(flag==0)
{
chess[x][y] = 0;
}
return 0;
}
int main(void)
{
int i, j;
//初始二维数组
for( i=0; i < X; i++ )
{
for( j=0; j < Y; j++ )
{
chess[i][j] = 0;
}
}
if(sethorse(1,0,1)) //如果函数返回值为1,则打印棋盘
{
for(i=0;i<X;i++)
{
for(j=0;j<Y;j++)
{
printf("%2d ",chess[i][j]);
}
printf("\n");
}
}
else
{
printf("未成功!!!");
}
return 0;
} |
|