一道BFS搜索题,详细步骤都写着了。
总结一下:
1、bfs搜索,用一个队列来实现,先放一个,然后队列头访问到的依次放入。然后pop,再下一个,如此操作。
2、学到了pair,确实挺好用的,pair<xx,xx>是将两个类型组合成一个类型,first,second方法可以访问其中第一个和第二个。
#include <iostream>
#include <algorithm>
#include <vector>
#include<functional>
#include<queue>
using namespace std;
int ori[8][2] = { {-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2} };//存八个方向
int visit[9][9] = {0};//用来判断该点是否跳到过,跳到过为1,就不用放到队列中去了
queue<pair<int, int>> q;//这个队列用来广度优先搜索
void bfs(int a, int b, int c, int d)
{
q.push({ a,b });//将第一个放入
visit[a][b] = 1;
int step = 1;//这个是需要走的步数
while (!q.empty())
{
//把队列中的第一个拿出来放手里开始广度优先
pair<int, int> now = q.front();
q.pop();//反正拿手里了,现在丢了也行
for (int i = 0;i < 8;i++)//八个方向遍历
{
int x = now.first + ori[i][0], y = now.second + ori[i][1];//分别代表了现在走到的xy的位置。
if (x == c && y == d)
{
//说明走到了目的地了,出来吧
cout << step;
return;
}
if (x >= 1 && x <= 8 && y >= 1 && y <= 8)//判断是棋盘上的点
{
q.push({ x,y });
}
}
//都做完一遍了,step+1
step++;
}
}
int main()
{
int a, b, c, d;//(a,b)为初始位置,(c,d)为最后终止位置
cin >> a >> b >> c >> d;
if (a == c && b == d)
{
cout << 0 << endl;
return 0;
}
bfs(a, b, c, d);
return 0;
}