#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<iostream>
#include<map>
#define N 510000
using namespace std;
struct node{
int a[10],x;
}p[N],tmp;
map<int,bool> b;
int ed=123804765,tail,ans[N];
void bfs()
{
int t=0;
tail=1;
for(int i=1;i<=9;i++) t=t*10+p[1].a[i];
b[t]=1;
if(t==ed) {printf("0\n");return;}

for(int i=1;i<=tail;i++)
{
int a[10],x;
for(int j=1;j<=9;j++) a[j]=p[i].a[j];
x=p[i].x;

if(x>=4)
{
for(int j=1;j<=9;j++) tmp.a[j]=a[j];
swap(tmp.a[x],tmp.a[x-3]);
tmp.x=x-3;
t=0;
for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
if(b.count(t)==0)
{
b[t]=1;
tail++;
p[tail]=tmp;
ans[tail]=ans[i]+1;
if(t==ed) {printf("%d\n",ans[tail]);return;}
}
}//上

if(x<=6)
{
for(int j=1;j<=9;j++) tmp.a[j]=a[j];
swap(tmp.a[x],tmp.a[x+3]);
tmp.x=x+3;
t=0;
for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
if(b.count(t)==0)
{
b[t]=1;
tail++;
p[tail]=tmp;
ans[tail]=ans[i]+1;
if(t==ed) {printf("%d\n",ans[tail]);return;}
}
}

if(x!=1 && x!=4 && x!=7)
{
for(int j=1;j<=9;j++) tmp.a[j]=a[j];
swap(tmp.a[x],tmp.a[x-1]);
tmp.x=x-1;
t=0;
for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
if(b.count(t)==0)
{
b[t]=1;
tail++;
p[tail]=tmp;
ans[tail]=ans[i]+1;
if(t==ed) {printf("%d\n",ans[tail]);return;}
}
}

if(x!=3 && x!=6 && x!=9)
{
for(int j=1;j<=9;j++) tmp.a[j]=a[j];
swap(tmp.a[x],tmp.a[x+1]);
tmp.x=x+1;
t=0;
for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
if(b.count(t)==0)
{
b[t]=1;
tail++;
p[tail]=tmp;
ans[tail]=ans[i]+1;
if(t==ed) {printf("%d\n",ans[tail]);return;}
}
}
}
}
int main()
{
for(int i=1;i<=9;i++)
{
char c=getchar();
p[1].a[i]=c-'0';
if(c=='0') p[1].x=i;
}
bfs();
return 0;
}

posted on 2019-07-16 17:02  Allen_lml  阅读(520)  评论(0编辑  收藏  举报