import scala.io.StdIn.{readInt,readLine}
import scala.collection.mutable.ArrayBuffer

object Main {
  def right(a:Array[Int],i:Int) = { val b = a.clone; b(i) = b(i+1); b(i+1) = 0;b }
  def left(a:Array[Int],i:Int) = { val b = a.clone; b(i) = b(i-1); b(i-1) = 0;b }
  def up(a:Array[Int],i:Int) = { val b = a.clone; b(i) = b(i-3); b(i-3) = 0;b }
  def down(a:Array[Int],i:Int) = { val b = a.clone; b(i) = b(i+3); b(i+3) = 0;b }
  def end(a:Array[Int], i:Int ) =
    a(0)==1 && a(1)==2 && a(2)==3 && a(3)==4 &&
    a(4)==5 && a(5)==6 && a(6)==7 && a(7)==8 && a(8)==0
  def contains(list:ArrayBuffer[(Int,Array[Int])], a:Array[Int]) =
    list.exists( _._2.sameElements(a) )

  def main(args:Array[String]) = { val p = new ArrayBuffer[Int]
    val hist= new ArrayBuffer[(Int,Array[Int])]
    var found = false
    var count = 0
    var idx = 0
    var result:Array[Int] = null
    for(i<-1 to 3) readLine.split(" ").map(_.toInt).foreach( p += _ )

    hist += ((p.indexWhere( _ == 0 ), p.toArray))

    while(!found && count<5) {
      val len = hist.length
      for(k<-idx until hist.length if !found) {
        val (i,e) = hist(k)
        if(i % 3 != 2) {
          val r = right(e, i)
          if(end(r,i)) { found = true; result = r }
          else if(!contains(hist,r)) hist += ((i+1,r))
        }
        if(!found && i % 3 != 0) {
          val r = left(e, i)
          if(end(r,i)) { found = true; result = r }
          else if(!contains(hist,r)) hist += ((i-1,r))
        }
        if(!found && i / 3 != 0) {
          val r = up(e, i)
          if(end(r,i)) { found = true; result = r }
          else if(!contains(hist,r)) hist += ((i-3,r))
        }
        if(!found && i / 3 != 2) {
          val r = down(e, i)
          if(end(r,i)) { found = true; result = r }
          else if(!contains(hist,r)) hist += ((i+3,r))
        }
      }
      idx += (len-idx)
      count += 1
    }
    println(count)
  }

}