AcWing 845. 八数码
原题链接
中等
作者:
dsyami
,
2021-06-04 15:23:51
,
所有人可见
,
阅读 276
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
int bfs(string state)
{
string end = "12345678x";
unordered_map<string, int> d;
queue<string> q;
q.push(state);
d[state] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while (q.size())
{
string t = q.front();
q.pop();
if (t == end) return d[t];
int distance = d[t];
int k = t.find('x');
int x = k / 3, y = k % 3;
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < 3 && b >= 0 && b < 3)
{
swap(t[k], t[a * 3 + b]);
if (!d.count(t))
{
d[t] = distance + 1;
q.push(t);
}
swap(t[k], t[a * 3 + b]);
}
}
}
return -1;
}
int main()
{
string state;
char c;
for (int i = 0; i < 9; i ++ )
{
cin >> c;
state += c;
}
cout << bfs(state) << endl;
return 0;
}