AcWing 845. 八数码[待完善]
原题链接
中等
作者:
晓龙coding
,
2021-10-28 16:53:14
,
所有人可见
,
阅读 202
普通搜索法:
#include<iostream>
#include<cstring>
#include<string>
#include<queue>
#include<unordered_map>
#include<algorithm>
using namespace std;
queue<string> q;
unordered_map<string, int> d;
int bfs(string s1, string s2) {
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };
q.push(s2);
d[s2] = 0;
while (q.size()) {
string t = q.front();
q.pop();
int idx = 0;
for (int i = 0; t[i]; i++) {
if (t[i] == 'x') {
idx = i;
break;
}
}
int x = idx / 3, y = idx % 3;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx < 0 || nx >= 3 || ny < 0 || ny >= 3) continue;
string tmp = t;
swap(tmp[idx], tmp[nx * 3 + ny]);
if (!d.count(tmp)) {
d[tmp] = d[t] + 1;
q.push(tmp);
}
if (tmp == s1) return d[tmp];
}
}
return -1;
}
int main() {
string s1 = "12345678x", s2;
for (int i = 0; i < 9; i++) {
char c;
cin >> c;
s2 += c;
}
int res = bfs(s1, s2);
cout << res << endl;
return 0;
}