|
|
|
Problem Description A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that
the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy. |
|
Sample Output
|
|
|
#if 1
#include<bits/stdc++.h>
using namespace std;
int step[8][8];
int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
bool pd(int x,int y)
{
if(x>=0 && x<=7 && y>=0 && y<=7)
return 1;
else return 0;
}
int starx,stary,endx,endy;
int bfs()
{
memset(step,0,sizeof(step));
queue <int>q;
int x,y,x1,y1;
q.push(starx);
q.push(stary);
step[x][y]=0;
while(!q.empty())
{
x=q.front();
q.pop();
y=q.front();
q.pop();
if(x==endx && y==endy) //看看现在的位置是不是
return step[x][y];
else
{
for(int i=0; i<=7; i++)
{
x1=x+dir[i][0];
y1=y+dir[i][1];
if(pd(x1,y1))
{
q.push(x1);
q.push(y1);
step[x1][y1]=step[x][y]+1;
}
}
}
}
}
int main()
{
char a[3],b[3];
while(cin>>a>>b)
{
starx=a[0]-'a';
stary=a[1]-'1';
endx=b[0]-'a';
endy=b[1]-'1';
int ans=bfs();
cout<<"To get from "<<a<<" to "<<b<<" takes "<<ans<<" knight moves."<<endl;
}
}
#endif

本文介绍了一种解决骑士在棋盘上从一点到另一点的最短移动路径问题的方法。利用广度优先搜索(BFS)算法,通过队列记录骑士可能到达的位置,并更新最短步数,最终找到两点间最小移动次数。
1186

被折叠的 条评论
为什么被折叠?



