#include<bits/stdc++.h>
#define ll long long
using namespace std;
int a;
int wx[4]={+1,-1,0,0},wy[4]={0,0,+1,-1};
queue <ll>q ;
map <ll,ll> dt ;//标记数组
int main(){
cin>>a;
q.push(a);
dt[a]=0;//bfs
while(!q.empty()){
ll tmp=q.front();q.pop();
ll b=tmp; int fx,fy;
if(tmp==123804765) break;//找到答案
short c[4][4];
for(int i=3;i>=1;i--){
for(int j=3;j>=1;j--){
c[i][j]=b%10;b/=10;
if(c[i][j]==0) fx=i,fy=j;//找空格来换
}
}
//把数字转存为二维数组
for(int i=0;i<4;i++){
int x=fx+wx[i],y=fy+wy[i];
if(x<1||y<1||x>3||y>3) continue;
swap(c[fx][fy],c[x][y]);
int a1;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
a1=a1*10+c[i][j];
}
}//转换成数字
if(dt[a1]!=0){
dt[a1]=dt[tmp]+1;
q.push(a1);
}//排除重复情况
swap(c[fx][fy],c[x][y]);//复原
}
}
cout<<dt[123804765];
return 0;
}