蓝桥杯 跳蚱蜢

题目:

如图 pic所示:


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

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

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

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

思路:

原字符串为“12345678*",目标字符串为"87654321*"。

每次空盘子可以和相邻或者相邻两个的位置交换。

考虑用BFS,记录下每次交换后的结果,如果以前没出现过,则步数加一,直至找到目标字符串。

#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;

string src = "12345678*";
string target = "87654321*";
unordered_set<string> vis;
class Node {
public:
	string str;
	int step;
	Node(string s, int num) {
		str = s;
		step = num;
	}
};

int dir[4] = {1, -1, 2, -2};

int bfs() {
	queue<Node> q;
	q.push(Node(src, 0));
	while (!q.empty()) {
		Node front = q.front();
		q.pop();
		if (front.str == target) {
			return front.step;
		}
		int pos = front.str.find('*');
		for (int i = 0; i < 4; i++) {
			string temp = front.str;
			int newPos = (pos + dir[i] + 9) % 9;
			swap(temp[pos], temp[newPos]);
			if (vis.count(temp) == 0) {
				vis.insert(temp);
				q.push(Node(temp, front.step + 1));
			}
		}
	}
	return -1;
}
	
int main()
{
   int res = bfs();
   cout << res << endl;
	
   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值