虽然是一道搜素,但还是有点麻烦。因为是求最优解,所以用到了队列,判重用哈希,就把状态看成一个九位数,用“map”不会超内存。
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
struct node
{
int state[9];
int step;
};
node start,target;
queue<node> q;
map<int,int>hash;
void init()
{
freopen("input.in","r",stdin);
freopen("output.txt","w",stdout);
}
int gethash(node st)
{
int s=0;
for (int i=0;i<9;i++) s=s*10+st.state[i];
return s;
}
void readdata()
{
char s[]="123804765";
for (int i=0;i<9;i++)target.state[i]=s[i]-'0';
//for (int i=0;i<9;i++)sscanf(s+i,"%1d",&target.state[i]);
for (int i=0;i<9;i++)scanf("%1d",&start.state[i]);
start.step=0;
q.push(start);
hash[gethash(start)]=1;
}
bool trytoinsert(node st)
{
int h=gethash(st);
if (hash[h]) return false;
hash[h]=1;
return true;
}
void check(node st)
{
if (gethash(st)==gethash(target))
{
printf("%d\n",st.step);
exit(0);
}
}
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
void work()
{
while(!q.empty())
{
node cur=q.front();
q.pop();
for (int i=0;i<4;i++)
{
node st;
memcpy(&st,&cur,sizeof(cur));
int zero=0;
for (zero=0;st.state[zero]!=0;zero++);
int x=zero/3;
int y=zero%3;
int newx=x+dx[i];
int newy=y+dy[i];
if (newx<0 || newx>2 || newy<0 || newy>2) continue;
int newzero=newx*3+newy;
st.state[zero]=st.state[newzero];
st.state[newzero]=0;
st.step++;
check(st);
if (trytoinsert(st)) q.push(st);
}
}
}
int main()
{
//init();
readdata();
work();
return 0;
}