题目:
如图 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;
}