#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
bool h[2][370000];
int step;
typedef struct nod
{
char s[10];
nod(){}
void write(){
puts(s);
}
}cstring;
queue< cstring > q[2];
int sta[3][3], end[3][3];
inline void read(int st[][3]) //读入函数
{
for(int i = 0; i < 3; i ++)
for(int j = 0; j < 3; j ++)
scanf("%d", &st[i][j]);
}
inline int nx(cstring str) //求逆序数
{
int l = strlen(str.s), i, j, num;
num = 0;
for(i = 0; i < l; i ++)
{
if(str.s[i] == '0') continue;
for(j = 0; j < i; j ++)
if(str.s[j] > str.s[i]) num ++;
}
//printf("%d\n",num);
return num;
}
inline int map(cstring str) //映射
{
int i, j, base, cnt, hash;
base = 1; hash = 0;
for(i = 0; i < 9; i ++)
{
if(str.s[i] == '0') str.s[i] = '9';
if(base == 0) base = 1;
base *= i; cnt = 0;
for(j = 0; j < i; j ++)
if(str.s[j] > str.s[i]) cnt ++;
hash += base * cnt;
}
return hash;
}
inline void swap(char &a, char &b) //交换函数
{
char c = a; a = b; b = c;
}
void change(cstring &tp, int dic) //4种扩展
{
int i, j, l = strlen(tp.s);
char tmp;
//up right down left
for(i = 0; i < l; i ++)
if(tp.s[i] == '0') break;
if(dic == 0 && i > 2)
swap(tp.s[i], tp.s[i - 3]);
else if(dic == 1 && i % 3 != 2)
swap(tp.s[i], tp.s[i + 1]);
else if(dic == 2 && i < 6)
swap(tp.s[i], tp.s[i + 3]);
else if(dic == 3 && i % 3 != 0)
swap(tp.s[i], tp.s[i - 1]);
else strcpy(tp.s, " ");
}
int extend(int index, cstring st) //扩展函数
{
cstring tp;
int i, j, l = strlen(st.s), hash;
for(i = 0; i < 4; i ++)
{
strcpy(tp.s ,st.s);
change(tp, i);
if(strcmp(tp.s," "))
{
//tp.write();
hash = map(tp);
if(h[index][hash]) continue;
if(h[1 - index][hash]) return true;
q[index].push(tp);
h[index][hash] = 1;
}
}
return false;
}
void atos(int arr[3][3], cstring &tp_atos) //把数组变成cstring
{
int i, j;
for(i = 0; i < 3; i ++)
for(j = 0; j < 3; j ++)
tp_atos.s[i * 3 + j] = arr[i][j] + '0';
tp_atos.s[9] = '\0';
}
int bfs()
{
cstring as, ed;
while(!q[0].empty()) q[0].pop();
while(!q[1].empty()) q[1].pop();
memset(h,0,sizeof(h));
atos(sta, as);
atos(end, ed);
if(nx(as) % 2 != nx(ed) % 2) return -1;//逆序奇偶性不同
q[0].push( as );
q[1].push( ed );
h[0][map( as )] = 1;
h[1][map( ed )] = 1;
if(h[0][map( ed )]) return 0; //两个相同
int index, size;
step = 0;
cstring temp;
while( !q[0].empty() || !q[1].empty() )
{
index = 0;
if( q[0].size() > q[1].size() ) index = 1; //取size小的先扩展
if( q[index].empty() ) index = 1 - index;
size = q[index].size();
while(size --)
{
temp = q[index].front();
//temp.write();
q[index].pop();
if( extend(index, temp) ) return step + 1; //扩展
}
step ++;
}
}
int main()
{
int ans = 0;
read(sta);
read(end);
ans = bfs();
printf("%d\n",ans);
}