蓝桥杯备赛---------跳蚱蜢

一、题目描述

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

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

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

运行限制

  • 最大运行时间:1s
  • 最大运行内存: 128M

二、代码实现

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <unordered_map> 

using namespace std;

int dx[] = {1, -1, 2, -2};

string st = "123456780", ed = "876543210";

int n = 9;

int bfs()
{
	unordered_map<string, int> dist;	//	dist[t]	存的是	从	st	到	t	的	最短步数 
	dist[st] = 0;
	queue<string> q;
	q.push(st);
	
	while (q.size())
	{
		auto t = q.front();
		q.pop();
		int k = t.find('0');
		for (int i = 0; i < 4; ++ i )
		{
			string str = t;
			swap(str[k], str[(k + dx[i] + n) % n]);
			if (dist.count(str))
				continue;
			dist[str] = dist[t] + 1;
			if (str == ed)
				return dist[str];
			q.push(str);
		}
	}
	
	return -1;
}

int main()
{
	cout << bfs() << endl;
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值