#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool inmp(int x,int y)
{
return x>=0&&x<3&&y>=0&&y<3;
}
int bfs(string str)
{
queue<string> q;
unordered_map<string,int> d;
// 哈希表存储出现过的字符串
q.push(str);
d[str]=0;
string end = "12345678x";
while(!q.empty())
{
auto t = q.front();
q.pop();
if(t==end) return d[t];
int dist = 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(inmp(a,b))
{
swap(t[a*3+b],t[k]);
if(!d[t])
{
d[t] = dist+1;
q.push(t);
}
swap(t[a*3+b],t[k]);
}
}
}
return -1;
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string str;
for(int i=0;i<9;i++)
{
char c;cin >> c;
str+=c;
}
cout << bfs(str) << endl;
return 0;
}
感谢查看