这道题很有典型示范意义, 将状态表示为字符串, 进行转移, 还有用到哈希表。
#include <iostream>
#include <queue>
#include <unordered_map>
#include <cstring>
#include <algorithm>
using namespace std;
int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
int bfs(string star)
{
string end = "12345678x";
unordered_map<string, int> hash;
queue<string> q;
q.push(star);
hash[star] = 0;
while(q.size())
{
string t = q.front();
q.pop();
int distance = hash[t];
if(t == end) return hash[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[b * 3 + a]);
if(hash[t] == 0)
{
q.push(t);
hash[t] = distance + 1;
}
swap(t[k], t[b * 3 + a]);
}
}
}
return -1;
}
int main()
{
string star;
for(int i = 0; i < 9; i ++)
{
char a;cin >> a;
star = star + a;
}
cout << bfs(star) << endl;
}