require 'set'

Move = [ [1, 3], [0, 2, 4], [1, 5],
         [0, 4, 6], [1, 3, 5, 7], [2, 4, 8],
         [3, 7], [4, 6, 8], [5, 7] ]

R = [0, 0, 0, 1, 1, 1, 2, 2, 2]
C = [0, 1, 2, 0, 1, 2, 0, 1, 2]

def min_heapify(x = 1)
  l = 2*x
  r = 2*x+1
  if l <= $n && $heap[l][0] < $heap[x][0]
    minimum = l
  else
    minimum = x
  end
  if r <= $n && $heap[r][0] < $heap[minimum][0]
    minimum = r
  end
  if minimum != x
    $heap[x], $heap[minimum] = $heap[minimum], $heap[x]
    min_heapify(minimum)
  end
end

def extract
  key = $heap[1]
  $heap[1] = $heap[$n]
  $n -= 1
  min_heapify
  key
end

def insert(key)
  $n += 1
  $heap[$n] = key
  i = $n
  while i > 1 && $heap[i/2][0] > $heap[i][0]
    $heap[i], $heap[i/2] = $heap[i/2], $heap[i]
    i /= 2
  end
end

def judge(brd, c)
  ret = c
  9.times do |i|
    if brd[i] > 0
      [R, C].each do |a|
        ret += (a[i] - a[brd[i] - 1]).abs
      end
    end
  end
  ret
end

brd = 3.times.map{ gets.split.map(&:to_i) }.flatten
$heap = []
$n = 0
insert [judge(brd, 0), brd, 0]
set = SortedSet.new([])
set.add(brd)
while $n > 0
  val, b, cnt = extract
  next if val > 45
  if val == cnt
    p cnt
    break
  end
  n = b.index(0)
  Move[n].each do |m|
    b[n], b[m] = b[m], b[n]
    nb = b.dup
    unless set.include?(nb)
      set.add(nb)
      insert [judge(b, cnt+1), nb, cnt + 1]
    end
    b[n], b[m] = b[m], b[n]
  end
end