题目:一个棋盘格9*10,按照象棋马走“日”的规则,从起点走到终点,且走过的路不能重新走,设计一个算法实现!
分析:
本题是典型的深度优先搜索的题目,首先分析马在一个位置时所能走的下一个位置时的走法,共有8种。如下图所示马所在位置所能到达的地方:
移动规则为:
int dx[] = {2,1,-1,-2,-2,-1,1,2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};
每次所能移动的位置的变量约束关系如上。具体如下代码所示:
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
struct horse{ //定义一个马
int sx,sy;
int iSetp;
};
bool visit[9][10]={0}; //定义 9*10大小的棋盘格
int dx[] = {2,1,-1,-2,-2,-1,1,2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};
bool Horse(int sx,int sy,int ex,int ey) // 主要程序
{
horse hor;
if(sx<0 || sx>8 || sy<0 || sy>9 || ex<0 || ex>8 || ey<0 ||ey>9)
{
cout<<"Error!"<<endl;
return false;
}
hor.sx = sx;
hor.sy = sy;
queue<horse> d;
d.push(hor);
if(hor.sx == ex && hor.sy == ey)
return true;
visit[sx][sy] = true;
while(hor.sx != ex || hor.sy != ey)
{
for(int i = 0 ; i < 8;i++)
{
hor = d.front();
//horse temp1;
cout<<"front:"<<hor.sx<<"::"<<hor.sy<<endl;
hor.sx += dx[i];
hor.sy += dy[i];
if(hor.sx < 0 || hor.sx >=9 || hor.sy < 0 || hor.sy >=10)
continue;
if(9>hor.sx>=0 && 10>hor.sy>=0)
{
if(visit[hor.sx][hor.sy] != true)
{
d.push(hor);
cout<<"d :"<<hor.sx<<"::"<<hor.sy<<endl;
if(hor.sx == ex && hor.sy == ey)
return true;
visit[hor.sx][hor.sy] = true;
}
}
}
d.pop();
if(d.empty())
{
return false;
}
hor = d.front();
}
}
int main(int argc,char** argv)
{
bool temp = Horse(8,9,8,8);
cout<<"result = "<<temp<<endl;
system("pause");
return 0;
}
Output: