AcWing 845. 八数码
原题链接
中等
作者:
术
,
2021-01-21 11:03:15
,
所有人可见
,
阅读 312
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int bfs(string start)
{
string end="12345678x";
queue<string> q;//将二维数据压缩为字符串,表示结点
unordered_map<string,int> d;//存储到达某状态的 距离
q.push(start);
d[start]=0;
while(!q.empty()){
string t=q.front();
q.pop();
int distance=d[t];
if(t==end) return distance;
//状态转移
int k=t.find('x');
int x=k/3,y=k%3;//取x坐标
for(int i=0;i<4;i++){
int xx=x+dx[i];
int yy=y+dy[i];
swap(t[k],t[xx*3+yy]);//状态更新
if(xx>=0&&xx<3&&yy>=0&&yy<3&&!d.count(t)){//未出现的结点才更新距离!!!!
d[t]=distance+1;
q.push(t);
}
swap(t[k],t[xx*3+yy]);//状态恢复 因为下一个位置变换页需要用原数据
}
}
return -1;
}
int main()
{
int x,y;
string start;//存储初始状态
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
{
char c;
cin>>c;
start+=c;
}
cout<<bfs(start)<<endl;
//cout << "Hello world!" << endl;
return 0;
}