蓝桥杯ALGO-1001跳马

一道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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值