以洛谷P1379 八数码难题为准,要用unordered_map头文件只有一个万能头文件是不够的,还需要加
#include<tr1/unordered_map>
using namespace std::tr1;
#include<bits/stdc++.h>
using namespace std;
#include<tr1/unordered_map>
using namespace std::tr1;
string end1="123804765";
string str;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
unordered_map<string,int>m;
queue<string>q;
int bfs(string str)
{
q.push(str);
m[str]=0;
while(!q.empty())
{
string t=q.front();
q.pop();
if(t==end1)return m[t];
int distance=m[t];
int k=t.find('0');
for(int i=0;i<4;i++)
{
int a=k/3+dx[i],b=k%3+dy[i];
if(a<0||a>=3||b<0||b>=3)continue;
int tmp=a*3+b;
swap(t[k],t[tmp]);
if(!m.count(t))
{
q.push(t);
m[t]=distance +1;
}
swap(t[k],t[tmp]);
}
}
}
int main()
{
cin>>str;
int res=bfs(str);
printf("%d",res);
return 0;
}