/*
set<matrix> s 存储地图状态
node{ matrix a; int t;}
乐观 估价函数 <= h()实际
283104765
123804765
h()==4 h*()=3
*/
//283104765 4
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string.h>
#include<queue>
#include<vector>
#include<bits/stdc++.h>
#define ll long long
#define ddd printf("-----------------------\n");
using namespace std;
const int maxn=1e1 +10;
const int mod=998244353;
const int inf=0x3f3f3f3f;
int dx[]={0, 0,1,0,-1};
int dy[]={0,-1,0,1, 0};
struct matrix{
int mp[5][5];
bool operator<(const matrix &x)const{
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
if(mp[i][j]!=x.mp[i][j]) return mp[i][j]<x.mp[i][j];
return 0;//all same also need to return val
}
}f,st;
int h(matrix x){
int res=0;
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
if(x.mp[i][j]!=st.mp[i][j])
res++;
return res;
}
struct node{
matrix a;
int t;
bool operator<(const node &x)const{//
return h(a)+t>h(x.a)+x.t;
}
};
priority_queue<node> q;
set<matrix> s;
int main()
{
st.mp[1][1]=1;st.mp[1][2]=2;st.mp[1][3]=3;
st.mp[2][1]=8;st.mp[2][2]=0;st.mp[2][3]=4;
st.mp[3][1]=7;st.mp[3][2]=6;st.mp[3][3]=5;
//ios::sync_with_stdio(false);
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++){
char ch; cin>>ch;
f.mp[i][j]=ch-'0';
// cout<<f.mp[i][j]<<' ';
// cout<<ch-'0'<<' ';
}
q.push({f,0});
while(q.size())
{
struct node u=q.top(); q.pop();
if(h(u.a)==0){ cout<<u.t<<'\n'; return 0;}
int fx,fy;
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
if(u.a.mp[i][j]==0) fx=i,fy=j;
for(int i=1;i<=4;i++){
int tx=fx+dx[i],ty=fy+dy[i];
if(tx>3||tx<1||ty>3||ty<1) continue;
swap(u.a.mp[fx][fy],u.a.mp[tx][ty]);
if(s.count(u.a)==0) s.insert(u.a),q.push({u.a,u.t+1});
swap(u.a.mp[fx][fy],u.a.mp[tx][ty]);
}
}
return 0;
}