国际象棋的马移动,分别向八个方向作广度优先搜索,找到最小步数。
BFS()简单应用。
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Point{
//点
int x;
int y;
};
struct QP{
//从开始到这点所需步数
Point p;
int move;
};
bool operator==(const Point &a,const Point &b){
//重载==
if(a.x == b.x && a.y == b.y)return true;
return false;
}
int way[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,-1},{2,1},{-1,-2},{1,-2}};
int steps(Point begin, Point end){
//计算最短步数
bool visited[8 + 1][8 + 1] = {0,0};
queue<QP> q;
QP current;
current.p = begin;
current.move = 0;
visited[current.p.x][current.p.y] = 1;
q.push(current);
while(!q.empty()){
current = q.front();
q.pop();
if(current.p == end)break;
for(int i=0; i<8; i++){
if(current.p.x + way[i][0] <= 8 && current.p.x + way[i][0] >= 1 && current.p.y + way[i][1] <= 8 && current.p.y + way[i][1] >= 1 && !visited[current.p.x + way[i][0]][current.p.y + way[i][1]]){
visited[current.p.x + way[i][0]][current.p.y + way[i][1]] = 1;
QP temp;
temp.p.x = current.p.x + way[i][0];
temp.p.y = current.p.y + way[i][1];
temp.move = current.move + 1;
q.push(temp);
}
}
}
return current.move;
}
int main(){
string s1,s2;
Point begin,end;
while(cin>>s1>>s2){
begin.y = s1[0] - 'a' + 1;
begin.x = s1[1] - '0';
end.y = s2[0] - 'a' + 1;
end.x = s2[1] - '0';
cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<steps(begin,end)<<" knight moves."<<endl;
}
return 0;
}
本文详细介绍了使用广度优先搜索(BFS)算法解决国际象棋中马的移动问题,通过计算从起始位置到目标位置的最短步数。文章包含代码实现和实例演示。

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



