知识点:广搜
难度:4
这个是状态图的搜索+打印路径,我状态的表示还是用的字符串,这种写法掌握的还是比较熟练的,这个应该是空间比较大可能效率也比较慢,等学了位运算的状压之后,再来优化时间复杂度和空间复杂度
#include <bits/stdc++.h>
using namespace std;
string s;
map<string, string> pre;
map<pair<string, string>, char> h;
int bfs() {
queue<string> q;
q.push("12345678");
unordered_map<string, int> mp;
mp["12345678"] = 0;
while (!q.empty()) {
string now = q.front(); q.pop();
if (now == s) return mp[s];
string t = now;
for (int i = 0; i < 4; i++) swap(t[i], t[7 - i]);
if (mp.find(t) == mp.end()) {
q.push(t); mp[t] = mp[now] + 1; pre[t] = now;
h[make_pair(t, now)] = 'A';
}
t = now;
char ch1 = t[3], ch2 = t[4];
for (int i = 0; i < 3; i++) {
t[3 - i] = t[2 - i];
t[4 + i] = t[5 + i];
}
t[0] = ch1; t[7] = ch2;
if (mp.find(t) == mp.end()) {
q.push(t); mp[t] = mp[now] + 1; pre[t] = now;
h[make_pair(t, now)] = 'B';
}
t = now;
char ch = t[2];
t[2] = t[1]; t[1] = t[6]; t[6] = t[5]; t[5] = ch;
if (mp.find(t) == mp.end()) {
q.push(t); mp[t] = mp[now] + 1; pre[t] = now;
h[make_pair(t, now)] = 'C';
}
}
return -1;
}
void print() {
vector<char> v;
while (s != "12345678") {
v.push_back(h[make_pair(s, pre[s])]);
s = pre[s];
}
reverse(v.begin(), v.end());
for (int i = 0; i < (int) v.size(); i++) cout << v[i];
}
int main() {
for (int i = 0; i < 8; i++) {
int x;
cin >> x;
s += x + '0';
}
cout << bfs() << '\n';
print();
return 0;
}