八数码
作者:
CarryJie
,
2021-09-08 16:57:44
,
所有人可见
,
阅读 318
#include <iostream>
#include <cstdio>
#include <queue>
#include <unordered_map>
using namespace std;
int dx[4] = {0,0,-1,1},dy[4] = {-1,1,0,0};
int bfs(string start)
{
string end = "12345678x";
queue<string> q;
unordered_map<string,int> dis;
q.push(start);
dis[start] = 0;
while(!q.empty())
{
string t = q.front();
q.pop();
int d = dis[t];
if(t == end)
return d;
int p = t.find('x');
int x = p / 3,y = p % 3;
for(int i = 0;i < 4;i ++)
{
int xx = x + dx[i],yy = y + dy[i];
if(xx >= 0 && xx < 3 && yy >= 0 && yy < 3)
{
swap(t[p],t[xx * 3 + yy]);
if(!dis.count(t))
{
dis[t] = d + 1;
q.push(t);
}
swap(t[p],t[xx * 3 + yy]);
}
}
}
return -1;
}
int main()
{
string start;
for(int i = 0;i < 9;i ++)
{
char c;
cin >> c;
start += c;
}
cout << bfs(start);
return 0;
}