思路:BFS求最短路,遇到终点直接结束
<span style="font-size:14px;">#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
int d[8][2] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
int begin1,begin2,end1,end2;
int chess[8][8];
struct Point{
int x,y;
int leng;
};
queue<Point> q;
int bfs()
{
int kase = 0;
Point begin,tmp;
begin.x = begin1;
begin.y = begin2;
begin.leng = 0;
q.push(begin);
while(!q.empty())
{
Point n;
n = q.front();
q.pop();
for(int i = 0;i<8;i++)
{
tmp.x = n.x+d[i][0];
tmp.y = n.y+d[i][1];
tmp.leng = n.leng + 1;
if (tmp.x==end1&&tmp.y==end2) return n.leng+1;
else
{
if(tmp.x>=0&tmp.x<8&tmp.y>=0&&tmp.y<8)
{
q.push(tmp);
}
}
}
}
}
int main()
{
char c[5],h[5];
while(scanf("%s %s", c, h) != EOF)
{
memset(chess,0,sizeof(chess));
while (!q.empty()) q.pop();
begin1 = c[0]-'a';
begin2 = c[1]-'1';
end1 = h[0] - 'a';
end2 = h[1] - '1';
int x;
if (begin1==end1&&begin2==end2) x = 0;
else x = bfs();
printf("To get from %s to %s takes %d knight moves.\n",c,h,x);
}
return 0;
}</span>

本文介绍了一种使用广度优先搜索(BFS)算法解决国际象棋中骑士从起点到终点最短移动次数的问题。通过定义骑士可能的移动方向,并采用队列存储待探索的状态,实现了高效的路径查找。

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



