rt。
我的代码,写挂了,求调。
#include <iostream>
#include <unordered_map>
using namespace std;
const int dx[]={0,1,0,-1},dy[]={-1,0,1,0};
void dfs(string &str,unordered_map<string,int> &ans,unordered_map<string,bool> &flag){
// cout<<str<<endl;
if (str=="123804765"){//如果直接是答案
return;
}
flag[str]=true;
int w1=str.find("0");//0在哪里
int x=w1/3,y=w1%3;//对应到底xy值
int res=0x3f3f3f3f;//这个点最小是多少
for (int i=0;i<4;++i){
int tx=x+dx[i],ty=y+dy[i];
if (tx<0 || tx>2 || ty<0 || ty>2){//如果越界了
continue;
}
int w2=tx*3+ty;//0应该在哪里
swap(str[w1],str[w2]);//交换
if (flag[str]){//如果成环
swap(str[w1],str[w2]);//记得交换回来
continue;
}
if (!ans[str]){//如果之前没搜过
dfs(str,ans,flag);//搜
}
res=min(res,ans[str]+1);//最小值一下
swap(str[w1],str[w2]);//交换回来
}
ans[str]=res;
flag[str]=false;
}
int main(){
string str;
cin >> str;
unordered_map<string,int> ans;
unordered_map<string,bool> flag;
dfs(str,ans,flag);
cout<<ans[str]<<endl;
return 0;
}