#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 10000;
string s,tar="123804765";
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
map<string, int> st;
queue<string> q;
int bfs(){
q.push(s);
st[s] = 0;
while(!q.empty()){
string cur = q.front(); q.pop();
if(cur==tar) return st[cur];
int t = cur.find('0');
int x=t/3, y=t%3;
for(int i=0;i<4;i++){
int nx=x+dx[i], ny=y+dy[i];
if(nx<0 || nx>=3 || ny<0 || ny>=3) continue;
int nt = nx*3 + ny;
string nxt = cur;
swap(nxt[t],nxt[nt]);
if(st.count(nxt)) continue;
st[nxt] = st[cur]+1;
q.push(nxt);
}
}
return -1;
}
int main(){
cin >> s;
cout << bfs();
return 0;
}