#include<bits/stdc++.h>
using namespace std;
struct node{
string s;
int step, f;
int id;
bool operator<(const node& y)const{
return f > y.f;
}
};
int xd[4] = {0, 0, 1, -1};
int yd[4] = {1, -1, 0, 0};
string s;
string cmp = "123804765";
set<string> st;
int h(string a){
int res = 0;
for(int i = 0; i < 9; i++){
if(a[i] == '0')continue; ///这里去点就卡样例12
//201534786
//19
if(cmp[i] != a[i])res++;
}
return res;
}
int Astar(){
if(!h(s))return 0;
int id = 0;
for(int i = 0; i < 9; i++){
if(s[i] == '0'){
id = i;
break;
}
}
priority_queue<node> q;
int step = h(s);
q.push(node{s, 0, step, id});
st.insert(s);
while(q.size()){
node p = q.top();
q.pop();
int idx = p.id / 3;
int idy = p.id % 3;
for(int i = 0; i < 4; i++){
int idxx = idx + xd[i];
int idyy = idy + yd[i];
if(idxx >= 0 && idxx < 3 && idyy >= 0 && idyy < 3){
int idd = idxx * 3 + idyy;
string ss = p.s;
swap(ss[p.id], ss[idd]);
if(st.find(ss) == st.end()){
st.insert(ss);
int hs = h(ss);
if(!hs){
return p.step + 1;
}
q.push(node{ss, p.step + 1, p.step + 1 + hs, idd});
}
}
}
}
return -1;
}
int main()
{
cin >> s;
cout << Astar();
return 0;
}