迭代加深
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<iostream>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<math.h>
#include<stdlib.h>
using namespace std;
#define M 400000
struct node
{
char s[20];
int pos;
}st;
int h[4]={-1,0,1,0};
int z[4]={0,1,0,-1};
char fa[]={"urdl"};
int path[M],limit;
int geth(char *s)//取得h,为当前位置与目标位置的manhattan距离
{
int i,j,h=0,x,y,x1,y1;
for(i=0;i<9;i++)
{
if(s[i]!='0')
{
x=i/3;
y=i%3;
x1=(s[i]-'0'-1)/3;
y1=(s[i]-'0'-1)%3;
h+=abs(x-x1)+abs(y-y1);
}
}
return h;
}
bool isAns(node t)
{
int i,j;
if(strcmp(t.s,"123456780")==0)
return 1;
return 0;
}
int judge(int x,int y)
{
return (x>=0&&x<3&&y>=0&&y<3);
}
int IDAstar(node t,int len)
{
if(len==limit)
{
return isAns(t);
}
int i,j,k,x,y;
for(i=0;i<4;i++)
{
if(len>0&&abs(i-path[len-1])==2)
continue;
node tp=t;
x=tp.pos/3;
y=tp.pos%3;
x+=h[i];
y+=z[i];
if(judge(x,y))
{
tp.pos=x*3+y;
swap(tp.s[tp.pos],tp.s[t.pos]);
path[len]=i;
if(geth(tp.s)+len<=limit&&IDAstar(tp,len+1))
return 1;
}
}
return 0;
}
void output()
{
int i,j,k;
for(i=0;i<limit;i++)
printf("%c",fa[path[i]]);
puts("");
}
int main()
{
int i,j,k;
char c;
for(i=0;i<9; )//读取字符串
{
scanf("%c",&c);
if(c == 'x')
{
st.s[i]='0';
st.pos=i;
i++;
}
else if(c>='0'&&c<='9')
{
st.s[i] = c;
i++;
}
else
continue;
}
st.s[9]='\0';
limit=geth(st.s);
while(!IDAstar(st,0))limit++;
output();
return 0;
}