#include<bits/stdc++.h>
using namespace std;
int bg,ed = 123804765;
int a[10];
map<int,int> m[2];
queue<pair<int,bool> > q;
bool check1(int x,int op){
for(int i = 9;i>0;i--) a[i] = x%10,x/=10;
int p;
for(int i = 9;i>=1;i--){
if(a[i]==0){
p = i;
break;
}
}
if(op==1){
if(p<=3) return -1;
else swap(a[p],a[p-3]);
}else if(op==2){
if(p>=7) return -1;
else swap(a[p],a[p+3]);
}else if(op==3){
if(p%3==1) return -1;
else swap(a[p],a[p-1]);
}else if(op==4){
if(p%3==0) return -1;
else swap(a[p],a[p+1]);
}
x = 0;
for(int i = 1;i<=9;i++) x = x*10+a[i];
return x;
}
void check2(int x,pair<int ,bool > h){
if(x==-1){
return ;
}
if(m[h.second^1].count(x)==true){
cout<<m[h.second^1][x]+m[h.second][h.first]+1<<endl;
exit(0);
} else{
m[h.second][x] = m[h.second][h.first]+1;
q.push(make_pair(x,h.second));
}
}
int main(){
cin>>bg;
if(bg==ed){
cout<<0;
return 0;
}
q.push(make_pair(bg,0));
q.push(make_pair(ed,1));
while(!q.empty()){
pair<int,bool> h = q.front();
q.pop();
int x = check1(h.first,1);check2(x,h);
x = check1(h.first,2);check2(x,h);
x = check1(h.first,3);check2(x,h);
x = check1(h.first,4);check2(x,h);
}
return 0;
}