蓝桥杯 跳蚱蜢

通过广度优先搜索算法解决蚱蜢从顺时针排列变为逆时针排列的问题,并保持空盘位置不变,最少需要20次跳跃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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


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


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



解:广搜,answer:20

#include <iostream>
#include <string>
#include <set>
#include <queue>
#include  <utility>
using namespace std;

string start = "012345678";
string e = "087654321";
int main() {
	queue<pair<string, int> > q;
	q.push(make_pair(start, 0));
	set<string> s;
	s.insert(start);
	while (!q.empty()) {
		string a = q.front().first;
		int level = q.front().second;
		if (a == e) {
			cout << level;
			break;
		}
		q.pop();
		int pos = 0;
		while (a[pos] != '0') pos++;
		int posi[4];
		posi[0] = (pos+8)%9;
		posi[1] = (pos+1)%9;
		posi[2] = (pos+7)%9;
		posi[3] = (pos+2)%9;
		for (int i = 0; i < 4; i++) {
			string b = a;
			b[pos] = b[posi[i]];
			b[posi[i]] = '0';
			if (s.count(b) == 0) {
				s.insert(b);
				q.push(make_pair(b, level+1));
			}
		}
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值