#include<bits/stdc++.h>
using namespace std;
int tran(int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9){
return (((((((((x1 * 10 + x2) * 10 + x3) * 10 + x4) * 10 + x5) * 10 + x6) * 10 + x7) * 10 + x8) * 10 + x9));
}
int main(){
int target = 123456789;
int first_grid = 0;
int p = pow(10, 9);
for(int i = 1, num;i <= 9;i++){
cin >> num;
p /= 10;
first_grid += num * p;
}
queue<pair<int, int> > bfs;
bfs.push({first_grid, 0});
set<int> st;
st.insert(first_grid);
if(first_grid == target){
cout << 0 << endl;
return 0;
}
while(true){
pair<int, int> a = bfs.front();
bfs.pop();
int grid = a.first;
int dis = a.second;
int x9 = grid % 10;
grid /= 10;
int x8 = grid % 10;
grid /= 10;
int x7 = grid % 10;
grid /= 10;
int x6 = grid % 10;
grid /= 10;
int x5 = grid % 10;
grid /= 10;
int x4 = grid % 10;
grid /= 10;
int x3 = grid % 10;
grid /= 10;
int x2 = grid % 10;
grid /= 10;
int x1 = grid % 10;
vector<int> aa;
aa.push_back(tran(x2, x1, x3, x4, x5, x6, x7, x8, x9));
aa.push_back(tran(x1, x3, x2, x4, x5, x6, x7, x8, x9));
aa.push_back(tran(x1, x2, x3, x5, x4, x6, x7, x8, x9));
aa.push_back(tran(x1, x2, x3, x4, x6, x5, x7, x8, x9));
aa.push_back(tran(x1, x2, x3, x4, x5, x6, x8, x7, x9));
aa.push_back(tran(x1, x2, x3, x4, x5, x6, x7, x9, x8));
aa.push_back(tran(x4, x2, x3, x1, x5, x6, x7, x8, x9));
aa.push_back(tran(x1, x5, x3, x4, x2, x6, x7, x8, x9));
aa.push_back(tran(x1, x2, x6, x4, x5, x3, x7, x8, x9));
aa.push_back(tran(x1, x2, x3, x7, x5, x6, x4, x8, x9));
aa.push_back(tran(x1, x2, x3, x4, x8, x6, x7, x5, x9));
aa.push_back(tran(x1, x2, x3, x4, x5, x9, x7, x8, x6));
for(int x : aa){
if(x == target){
cout << dis + 1 << endl;
return 0;
}
int pre = st.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