#include<iostream>
#include<string>
#include<unordered_map>
#include<queue>
using namespace std;
int dx[] = {-1,0,1,0};
int dy[] ={0,1,0,-1};
string end1 = "123804765";
unordered_map<string,int> dist;
unordered_map<string,int>vis;
queue<string> q;
int bfs(string start){
q.push(start);
q.push(end1);
dist[start] = 0,dist[end1] = 0;
vis[start] = 1,vis[end1] = 2;
while(q.size()){
auto t = q.front();
q.pop();
cout<<"pop:"<<t<<endl;
int a = t.find('0');
int x1 = a / 3, y1 = a % 3;
for(int i = 0; i < 4; i ++){
int x2 = dx[i] + x1, y2 = dy[i] + y1;
if(x2 < 0 || x2 >= 3 || y1 < 0 || y2 >= 3) continue;
int temp = x2 * 3 + y2;
string new_state = t;
cout<<"a:"<<a<<" "<<"temp:"<<temp<<endl;
swap(new_state[a],new_state[temp]);
if(vis[t] + vis[new_state] == 3){
return dist[new_state] + dist[t] + 1;
}
if(!dist.count(new_state))
{
dist[new_state] = dist[t] + 1;
vis[new_state] = vis[t];
q.push(new_state);
cout<<"new_state:"<<new_state<<endl;
}
}
}
return -1;
}
int main(){
string s;
cin>>s;
int res = bfs(s);
cout<<res<<endl;
return 0;
}