rt
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){
int x=0,f=1;
char ch=getchar();
while (ch<'0'||ch>'9'){
if (ch=='-')
f=-1;
ch=getchar();
}
while (ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+ch-48;
ch=getchar();
}
return x*f;
}
inline void put(int x)
{
if (x > 9) put(x / 10);
putchar(x % 10 + 48);
}
map<string,bool> mp;
struct node{
string s;
int sum,weizhix,weizhiy;
};
int weizhix_0,weizhiy_0;
string s;
void bfs(string s){
queue<node> q;
q.push({s,0,weizhix_0,weizhiy_0});
mp[s]=true;
while(q.empty()==false){
node cur=q.front();
q.pop();
if(cur.s==" 123804765"){
cout<<cur.sum;
exit(0);
}
if(cur.weizhix!=1){
string nw_s=cur.s;
swap(nw_s[(cur.weizhix-2)*3+cur.weizhiy],nw_s[(cur.weizhix-1)*3+cur.weizhiy]);
if(mp[nw_s]==false){
mp[nw_s]=true;
q.push(node{nw_s,cur.sum+1,cur.weizhix-1,cur.weizhiy});
}
}
if(cur.weizhix!=3){
string nw_s=cur.s;
swap(nw_s[(cur.weizhix-1)*3+cur.weizhiy],nw_s[cur.weizhix*3+cur.weizhiy]);
if(mp[nw_s]==false){
mp[nw_s]=true;
q.push(node{nw_s,cur.sum+1,cur.weizhix+1,cur.weizhiy});
}
}
if(cur.weizhiy!=1){
string nw_s=cur.s;
swap(nw_s[(cur.weizhix-1)*3+cur.weizhiy-1],nw_s[(cur.weizhix-1)*3+cur.weizhiy]);
if(mp[nw_s]==false){
mp[nw_s]=true;
q.push(node{nw_s,cur.sum+1,cur.weizhix,cur.weizhiy-1});
}
}
if(cur.weizhiy!=3){
string nw_s=cur.s;
swap(nw_s[(cur.weizhix-1)*3+cur.weizhiy],nw_s[(cur.weizhix-1)*3+cur.weizhiy+1]);
if(mp[nw_s]==false){
mp[nw_s]=true;
q.push(node{nw_s,cur.sum+1,cur.weizhix,cur.weizhiy+1});
}
}
}
return;
}
signed main(){
cin>>s;
s=" "+s;
for(int i=1; i<=9; i++)
if(s[i]=='0')
weizhix_0=(i-1)/3+1,weizhiy_0=i%3;
bfs(s);
return 0;
}