#include<bits/stdc++.h> 
using namespace std; 
#define endl "\n" 
#define fi first 
#define se second 
#define tn int
#define thaonguyen( i, a, b ) for( tn i = a; i <= b; i++ )
#define nguyenthao( i, a, b ) for( tn i = a; i >= b; i-- )
#define thaonguyenxinh ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); 
char chr;
tn cost;
string s, u; 
queue< pair< string, tn > > q;
unordered_set< string > st; 
void move( tn position, tn type ){
    if ( type == 1 ){
        if ( position != 2 and position != 5 and position != 8 ){
           swap( u[position], u[position+1] );
            if ( st.find( u ) == st.end() ){
                    st.insert(u);
                    q.push( { u, cost + 1 } );
                } 
            swap( u[position], u[position+1] );
        }
    }
    if ( type == 2 ){
        if ( position != 0 and position != 3 and position != 6 ){
            swap( u[position], u[position-1] );
            if ( st.find( u ) == st.end() ){
                    st.insert(u);
                    q.push( { u, cost + 1 } );
                } 
           swap( u[position], u[position-1] );
        }
    }
    if ( type == 3 ){
        if ( position != 6 and position != 7 and position != 8 ){
           swap( u[position], u[position+3] );
            if ( st.find( u ) == st.end() ){
                    st.insert(u);
                    q.push( { u, cost + 1 } );
                } 
            swap( u[position], u[position+3] );
        }
    }
    if ( type == 4 ){
        if ( position != 0 and position != 1 and position != 2 ){
            swap( u[position], u[position - 3] );
            if ( st.find( u ) == st.end() ){
                    st.insert(u);
                    q.push( { u, cost + 1 } );
                } 
            swap( u[position], u[position - 3] );
        }
    }
}
void cfs(){
    q.push( { s , 0 } );
    while ( !q.empty() ){
        u = q.front().fi; 
        cost = q.front().se;
        if ( u == "123456789" ){
            cout << q.front().se; 
            break;
        }
        q.pop(); 
        thaonguyen( i, 0, s.size() - 1 )
            thaonguyen( j, 1, 4 ){
                move( i, j );
                
            }
    }
}
signed main(){
    thaonguyenxinh
    thaonguyen( i, 1, 9 )
        cin >> chr, 
        s += chr;
    st.insert(s);
    cfs();
}