一、题目描述
如下图所示: 有 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;
}