蓝桥杯 跳蚱蜢(BFS)

题目链接

题目:

pic
如图 pic所示:
有9只盘子,排成1个圆圈。
其中8只盘子内装着8只蚱蜢,有一个是空盘。
我们把这些蚱蜢顺时针编号为 1~8

每只蚱蜢都可以跳到相邻的空盘中,
也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。

请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列,
并且保持空盘的位置不变(也就是1-8换位,2-7换位,…),至少要经过多少次跳跃?

注意:要求提交的是一个整数,请不要填写任何多余内容或说明文字。

解题思路:本题通过map存储字符串判断是否进入队列,先找到空杯子的位置然后对能跳到空杯子的位置进行交换,具体可以看代码。因为只是个填空题所以通过string存储,效率较低。

代码:

#include<cstdio>
#include<algorithm> 
#include<iostream>
#include<string>
#include<map>
#include<queue>
using namespace std;
struct node{
	int step;
	string s;
};
int X[4] = {-2,-1,1,2};
string start = "*87654321";
string end = "*12345678";
map<string,int> vis;
int BFS(){
	queue<node> q;
	node Node;
	Node.step = 0;
	Node.s = start;
	q.push(Node);
	while(!q.empty()){
		node front = q.front();
		q.pop();
		if(front.s == end)
			return front.step;
		int pos = front.s.find("*");
		for(int i = 0 ; i < 4;i++){
			string temp = front.s;
			int nowpos = (pos + X[i]+9)%9;
			swap(temp[pos],temp[nowpos]);
			if(vis[temp] == 0){
				vis[temp] = 1;
				Node.s = temp;
				Node.step = front.step + 1;
				q.push(Node);
			}
		}
	}
}
int main(void){
	int ans = BFS();
	cout << ans;
	return 0;
}
发布了69 篇原创文章 · 获赞 5 · 访问量 2002

猜你喜欢

转载自blog.csdn.net/lovingcgq/article/details/105477339