题目链接:https://www.acwing.com/problem/content/description/847/
题目如下:
#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
int bfs(string start){
string end="12345678x";
queue<string> que;//用来记录每次变换后的状态
unordered_map<string,int> umap;//记录从最开始,到最后目标状态,每一转换的顺序次数
que.push(start);
umap[start]=0;
while(que.size()){
auto t=que.front();
que.pop();
int distance=umap[t];
if(t==end) return distance;
//状态转移
int pos=t.find('x');//返回字符x所在string中的位置
int x=pos/3,y=pos%3;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
for(int i=0;i<4;i++){
int a=x+dx[i];
int b=y+dy[i];
if(a>=0&&a<3&&b>=0&&b<3){
swap(t[pos],t[a*3+b]);//当前x向其他方向走动
if(umap[t]==0){//用来判断umap中是否已经存有t,如果更新过的t没有更新过,则找到了一个新的状态
umap[t]=distance+1;
que.push(t);
}
swap(t[pos],t[a*3+b]);//这里要恢复状态,因为要对下一个方向做判断,看能不能转换,因为四个方向遍历算作一次操作
}
}
}
return -1;
}
int main(){
string start="";
for(int i=0;i<9;i++){
char c;
cin>>c;
start+=c;
}
cout<<bfs(start)<<endl;
return 0;
}