搜索,哈希判重
#include<bits/stdc++.h>
using namespace std;
bool vis[65540];
int dx[4]={0,0,1,-1};
int dy[4]={-1,1,0,0};
struct sta{
int a[5][5];
int step;
}bg,ed;
int hash_ed;
int ha(sta a){
int ret=0;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
ret=2*ret+a.a[i][j];
return ret;
}
void bfs(sta u){
queue<sta>q;
q.push(u);
vis[ha(u)]=1;
while(!q.empty()){
u=q.front();
q.pop();
int aha=ha(u);
if(aha==hash_ed){
ed.step=u.step;
break;
}
for(int i=1;i<=4;i++){
for(int j=1;j<=4;j++){
if(u.a[i][j]==0) continue;
for(int k=0;k<4;k++){
int xx=i+dx[k],yy=j+dy[k];
if(xx>4||xx<1||yy>4||yy<1) continue;
if(u.a[xx][yy]==0){
swap(u.a[i][j],u.a[xx][yy]);
u.step+=1;
int tmp=ha(u);
if(!vis[tmp]){
q.push(u);
vis[tmp]=1;
}
swap(u.a[i][j],u.a[xx][yy]);
u.step-=1;
}
}
}
}
}
}
int main(){
char str[5];
for(int i=1;i<=4;i++){
scanf("%s",str);
for(int j=1;j<=4;j++)
bg.a[i][j]=str[j-1]-'0';
}
bg.step=0;
for(int i=1;i<=4;i++){
scanf("%s",str);
for(int j=1;j<=4;j++)
ed.a[i][j]=str[j-1]-'0';
}
hash_ed=ha(ed);
bfs(bg);
printf("%d\n",ed.step);
return 0;
}