题目描述:
题解: BFS+HASH~~ 第一次用hash,之前一直超时。
代码:
#include<iostream>
#include<cstdio>
char star[10],send[10];
int nodedir=0,exdir=0;
bool visit[200000000]={0};
int dir[4][2]={
{0,1},
{0,-1},
{1,0},
{-1,0},
};
const int Max=200000;
struct Node{
int a[3][3],x,y,step;
} map[Max],temp,end;
int hash(Node x)
{
int num=1,sum=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(x.a[i][j])
{
num=x.a[i][j];
for(int k=0;k<i*3+j;k++)
num*=8;
sum+=num;
}
return sum;
}
int main()
{
scanf("%s%s",star,send);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(star[i*3+j]>'0'&&star[i*3+j]<'9')
map[0].a[i][j]=star[i*3+j]-'0';
else if(star[i*3+j]=='.'){
map[0].a[i][j]=0;
map[0].x=i; map[0].y=j;
}
if(send[i*3+j]>'0'&&send[i*3+j]<'9')
end.a[i][j]=send[i*3+j]-'0';
else{ end.a[i][j]=0;
end.x=i; end.y=j;
}
}
visit[hash(end)]=1;
visit[hash(map[0])]=1;
map[0].step=0;
while(nodedir<=exdir&&exdir<Max)
{
for(int i=0;i<4;i++)
{
temp=map[nodedir];
int dx=temp.x+dir[i][0],dy=temp.y+dir[i][1];
if(dx>=0&&dx<3&&dy>=0&&dy<3)
{
int t;
t=temp.a[temp.x][temp.y];
temp.a[temp.x][temp.y]=temp.a[dx][dy];
temp.a[dx][dy]=t;
temp.x=dx; temp.y=dy; temp.step++;
if(hash(temp)==hash(end))
{
printf("%d\n",temp.step);
return 0;
}
if(!visit[hash(temp)])
map[++exdir]=temp;
visit[hash(temp)]=1;
}
}
nodedir++;
}
printf("-1\n");
return 0;
}
蓝桥杯OJ PREV-19 九宫重排,布布扣,bubuko.com
原文:http://blog.csdn.net/mummyding/article/details/38382631