#include <bits/stdc++.h>
using namespace std;
map<string,int> m;
map<string,bool> m1;
queue<string> q;
signed main() {
string s;
cin>>s;
q.push(s);
m[s]=0;
m1[s]=true;
while(!q.empty()) {
string p=q.front(),p1;
q.pop();
if(p=="123804765") {
cout<<m[p];
break;
}
for(int i=0;i<9;i++) {
if(p[i]=='0') {
p1=p;
if(i-3>=0) swap(p1[i],p1[i-3]);
if(!m1[p1]&&i-3>=0) {
q.push(p1);
m[p1]=m[p]+1;
m1[p1]=true;
}
p1=p;
if(i+3<=8) swap(p1[i],p1[i+3]);
if(!m1[p1]&&i+3<=8) {
q.push(p1);
m[p1]=m[p]+1;
m1[p1]=true;
}
p1=p;
if(i-1>=0) swap(p1[i],p1[i-1]);
if(!m1[p1]&&i-1>=0) {
q.push(p1);
m[p1]=m[p]+1;
m1[p1]=true;
}
p1=p;
if(i+1<=8) swap(p1[i],p1[i+1]);
if(!m1[p1]&&i+1<=8) {
q.push(p1);
m[p1]=m[p]+1;
m1[p1]=true;
}
break;
}
}
}
}