#include<iostream>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
#define Ntw 3
#define N2tw 9

struct Puzzletw{
    int f[N2tw];
    int space;
    string path;

    bool operator < (const Puzzletw &p)const{
        for(int i=0;i<N2tw;i++){
            if(f[i]==p.f[i])continue;
            return f[i]>p.f[i];
        }
        return false;
    }
};

static const int dx[4]={-1,0,1,0};
static const int dy[4]={0,-1,0,1};
static const char dir[4]={'u','l','d','r'};

bool isTarget(Puzzletw p){
    for(int i=0;i<N2tw;i++)
    if(p.f[i] != (i+1))return false;
    return true;
}

string bfs(Puzzletw s){
    queue<Puzzletw> Q;
    map<Puzzletw,bool>V;
    Puzzletw u, v;
    s.path="";
    Q.push(s);
    V[s]=true;

    while(!Q.empty()){
        u=Q.front();Q.pop();
        if(isTarget(u))return u.path;
        int sx = u.space/Ntw;
        int sy = u.space%Ntw;
        for(int r=0;r<4;r++){
            int tx=sx+dx[r];
            int ty=sy+dy[r];
            if(tx<0||ty<0||tx>=Ntw||ty>=Ntw)continue;
            v=u;
            swap(v.f[u.space],v.f[tx*Ntw+ty]);
            v.space=tx*Ntw+ty;
            if(!V[v]){
                V[v]=true;
                v.path+=dir[r];
                Q.push(v);
            }
        }
    }

    return "unsolvable";
}

int main(){
    Puzzletw in;

    for(int i=0;i<N2tw;i++){
        cin >> in.f[i];
        if(in.f[i]==0){
            in.f[i]=N2tw;
            in.space=i;
        }
    }
    string ans = bfs(in);
    cout << ans.size()<<endl;

    return 0;
}

