思路:
此题使用bfs有些抽象,不像迷宫哪些容易想到,不知道如何扩散。
开始思路是以空格坐标作为参数,把能到达当前空格坐标的所有点加入队列,当空格位于N+1的位置且左右两边的符号不同时,说明棋子归位了。对于查找问题,unordered_map会更加高效一些,因此遇到查找问题,常会考虑一下用unordered_map。本次在标记字符串时用了unordered_map,在查询方面较快
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;
int N;
struct node {
string s; //当前序列
int pos; //当前空格位置
vector<int> step; //从开始到当前所有空格位置
node() {}
node(string ss, int p) {
s = ss;
pos = p;
}
};
unordered_map<string, bool> mp;
string Strswap(string s, int a, int b) {
char c = s[a];
s[a] = s[b];
s[b] = c;
return s;
}
queue<node> q;
int main() {
scanf("%d", &N);
string s1, s2; //正逆向序列
for (int i = 0; i < N; ++i) {
s1 += '1';
s2 += "2";
}
s1 += "0";
s2 += "0";
for (int i = 0; i < N; ++i) {
s1 += "2";
s2 += "1";
}
//printf("%s\n%s",s1.c_str(),s2.c_str());
int dir[4] = { -2,-1,1,2 }; //每个空格有四个变化位置
q.push(node(s1, N));
mp[s1] = true;
while (!q.empty()) {
node now = q.front();
q.pop();
//判断是否成功
if (now.s == s2) {
int cnt = 0;
for (int i = 0; i < now.step.size(); ++i) {
if (cnt == 4) {
printf("%d\n", now.step[i] + 1); //+1的目的使数组下标从1开始
cnt = 0;
}
else {
printf("%d ", now.step[i] + 1);
cnt++;
}
}
break;
}
//空格变化
for (int i = 0; i < 4; ++i) { //为什么不需要判断下一步是否合理,BFS搜到最短路径到达目标即停止,所以该路径存储的空格位置即为正确答案
int tp = now.pos + dir[i];
if (tp >= 0 && tp < 2 * N + 1) {
string ts = Strswap(now.s, now.pos, tp);
if (!mp[ts]) {
mp[ts] = true;
node tn = node(ts, tp);
tn.step = now.step;
tn.step.push_back(tp);
q.push(tn);
cout << tp << endl;
}
}
}
}
while (1);
return 0;
}