求从他给的坐标走到另一个坐标需要多少步数,字母数字代表行列
走的规则就像马走日一样(可以先横走一步再竖两步,或者竖两步横一步一共有八个方向)
#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
char map[9][9];
int judge[9][9];
int s1,s2,e1,e2;
string a,b;
int rule[8][2] = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node
{
int step;
int fx,fy;
};
int bfs()
{
queue<node> que;
node pre,next;
pre.fx = s1;
pre.fy = s2;
pre.step = 0;
que.push(pre); //先把第一次压入队列
memset(judge,0,sizeof(judge)); //清空标记的数组
judge[s1][s2] = 1; //第一次标记
while (!que.empty())
{
pre = que.front(); //取出队列中的第一个
que.pop(); //删除
if(pre.fx == e1 && pre.fy ==e2)
return pre.step;
for (int i = 0; i < 8; i++)
{ //符合条件
if (pre.fx+rule[i][0]<9 && pre.fx+rule[i][0]>0 &&
pre.fy+rule[i][1]<9 && pre.fy+rule[i][1]>0 &&
judge[pre.fx+rule[i][0]][pre.fy+rule[i][1]] == 0)
{ //【保持pre不动 动的只有next节点,再将next压入队列】
next.fx= pre.fx+rule[i][0];
next.step=pre.step+1;
next.fy = pre.fy+rule[i][1];
judge[next.fx][next.fy] = 1; //标记,不走回头路
que.push(next);
}
}
}
return 0;
}
int main()
{
while (cin>>a>>b)
{
s1 = a[0]-'a'+1;
s2 = a[1]-'0';
e1 = b[0]-'a'+1;
e2 = b[1]-'0';
cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
}
return 0;
}

本文介绍了一个使用广度优先搜索(BFS)算法解决骑士在棋盘上从一个位置移动到另一个位置所需最少步数的问题。通过定义骑士的移动规则,并采用队列实现BFS算法,最终输出从起始位置到目标位置所需的最小移动次数。
407

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



