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

object Main {
  def right(m:scala.collection.immutable.Map[Int,Int],i:Int):Map[Int,Int] = m.updated(i, m(i+1)).updated(i+1,0)
  def left(m:Map[Int,Int],i:Int):Map[Int,Int] = m.updated(i, m(i-1)).updated(i-1,0)
  def up(m:Map[Int,Int],i:Int):Map[Int,Int] = m.updated(i, m(i-3)).updated(i-3,0)
  def down(m:Map[Int,Int],i:Int):Map[Int,Int] = m.updated(i, m(i+3)).updated(i+3,0)
  def end(m:Map[Int,Int]) = m == Map(0->1,1->2,2->3,3->4,4->5,5->6,6->7,7->8,8->0)

  def main(args:Array[String]) = {
    val p = new HashMap[Int,Int]
    val hist= new HashMap[scala.collection.immutable.Map[Int,Int], Int]
    var found = false
    var count = 0
    var idx = 0
    var k = 0
    var l = 0
    for(i<-1 to 3) {
      readLine.split(" ").map(_.toInt).foreach{ x=>
        p += (k->x)
        if(x==0) l = k
        k+=1
      }
    }

    hist += (p.toMap->l)
    while(!found) {
      val hist2 = new HashMap[scala.collection.immutable.Map[Int,Int], Int]
      for((m,i)<-hist if !found) {
        if(i % 3 != 2) {
          val r = right(m, i)
          if(end(r)) found = true
          else if(!hist.contains(r)) hist2 += (r->(i+1))
        }
        if(!found && i % 3 != 0) {
          val r = left(m, i)
          if(end(r)) found = true
          else if(!hist.contains(r)) hist2 += (r->(i-1))
        }
        if(!found && i / 3 != 0) {
          val r = up(m, i)
          if(end(r)) found = true
          else if(!hist.contains(r)) hist2 += (r->(i-3))
        }
        if(!found && i / 3 != 2) {
          val r = down(m, i)
          if(end(r)) found = true
          else if(!hist.contains(r)) hist2 += (r->(i+3))
        }
      }
      if(!found) hist ++= hist2
      count += 1
    }
    println(count)
  }

}