#include <bits/stdc++.h>
using namespace std;
struct sa{
int n;
int step;
}q[10000001];
int ql=1,qr=0,n;
int dx[]={-1,0,0,1};
int dy[]={0,-1,1,0};
map<int,int>mp;
int zt[3][3];
int ans=123804765;
int main()
{
cin>>n;
q[++qr]={n,0};
mp[n]=1;
while(ql<=qr){
if(q[ql].n==ans){
cout<<q[ql].step;
break;
}
int x=q[ql].n,x0,y0;
for(int i=2;i>=0;i--){
for(int j=2;j>=0;j--){
if(n%10==0)x0=i,y0=j;
zt[i][j]=n%10,n/=10;
}
}
for(int i=0;i<4;i++){
int tx=x0+dx[i],ty=y0+dy[i];
if(tx>=0&&ty>=0&&tx<3&&ty<3){
swap(zt[tx][ty],zt[x0][y0]);
int a=0;
for(int j=0;j<3;j++){
for(int k=0;k<3;k++)
a=a*10+zt[j][k];
}
if(!mp.count(a)){
mp[a]=1;
cout<<a<<endl;
q[++qr]={a,q[ql].step+1};
}
swap(zt[tx][ty],zt[x0][y0]);
}
}
ql++;
}
return 0;
}