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]
Factorials = (1...9).each_with_object([1]){ |i, arr| arr << arr[-1] * i }.reverse

def create_hash(brd)
  b = brd.dup
  9.times do |i|
    (i+1...9).each do |j|
      b[j] -= 1 if b[i] < b[j]
    end
  end
  9.times.reduce(0){ |sum, i| sum += b[i] * Factorials[i] }
end

def dehash(key)
  brd = 9.times.map { |i| d, key = key.divmod(Factorials[i]); d }
  8.downto(0) do |i|
    (i+1...9).each do |j|
      brd[j] += 1 if brd[j] >= brd[i]
    end
  end
  brd
end

def judge(brd)
  ret = 0
  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

Goal = create_hash([1,2,3,4,5,6,7,8,0])

brd = 3.times.map{ gets.split.map(&:to_i) }.flatten
q = [[judge(brd), k = create_hash(brd), 0]]
ans = -1
set = Set.new([])
set.add(k)
until q.empty?
  arr = q.min{ |a, b| a <=> b }
  q.delete(arr)
  _, key, cnt = arr
  if key == Goal
    ans = cnt
    break
  end
  b = dehash(key)
  n = b.index(0)
  Move[n].each do |m|
    b[n], b[m] = b[m], b[n]
    k = create_hash(b)
    unless set.include?(k)
      set.add(k)
      q << [judge(b), k, cnt + 1]
    end
    b[n], b[m] = b[m], b[n]
  end
end
p ans