<span style="font-size:18px;">//1.广搜,参考网址:http://www.cnblogs.com/jackge/archive/2013/03/28/2986804.html 本来是想用数组实现队列的但是mle了///于是改着改着就和网上的一样了。。。</span>
<span style="font-size:18px;">#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
typedef int State[9];
const int maxn = 1000000;
string path;
char c,indexs[5]="udlr";//正向搜索
struct node{
State s;
int loc; //“0”的位置,把“x"当0
int status; //康拖展开的hash值
string path; //路径
};
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};//u,d,l,r
int fac[]={1,1,2,6,24,120,720,5040,40320,362880}; //康拖展开判重
// 0!1!2!3! 4! 5! 6! 7! 8! 9!
int aim=46234,vis[maxn]; //123456780对应的康拖展开的hash值
node ncur;
int Cantor(int s[]){ //康拖展开求该序列的hash值
int sum=0;
for(int i=0;i<9;i++){
int cnt=0;
for(int j=i+1;j<9;j++)
if(s[i]>s[j])
cnt++;
sum+=(cnt*fac[9-i-1]);
}
return sum+1;
}
int bfs()
{
queue<node> q;
while(!q.empty())
q.pop();
node cur,next;
q.push(ncur);
while(!q.empty())
{
cur=q.front();
q.pop();
if(cur.status==aim){
path=cur.path;
return 1;
}
int x=cur.loc/3,y=cur.loc%3;
for(int d=0;d<4;d++)
{
int newx=x+dir[d][0];
int newy=y+dir[d][1];
if(newx>=0&&newx<3&&newy>=0&&newy<3)
{
next=cur;
next.loc=newx*3+newy;
next.s[cur.loc]=next.s[next.loc];
next.s[next.loc]=0;
next.status=Cantor(next.s);
if(!vis[next.status])
{
vis[next.status]=1;
next.path=next.path+indexs[d];
if(next.status==aim)
{
path=next.path;
return 1;
}
q.push(next);
}
}
}
}
return 0;
}
int main()
{
while(cin>>c)
{
if(c=='x')
{
ncur.s[0]=0;
ncur.loc=0;
}
else ncur.s[0]=c-'0';
for(int i=1;i<9;i++)
{
cin>>c;
if(c!='x')ncur.s[i]=c-'0';
else if(c=='x')
{
ncur.s[i]=0;
ncur.loc=i;
}
}
ncur.status=Cantor(ncur.s);
memset(vis,0,sizeof(vis));
if(bfs())
cout<<path<<endl;
else
printf("unsolvable\n");
getchar();
}
return 0;
}</span>