# ???????????¢??¶?????????
target_panels = []
3.times do |i|
  target_panels << STDIN.gets.chomp.split(' ').map(&:to_i)
end
target_panels.flatten!

first_panels = [1, 2, 3, 4, 5, 6, 7, 8, 0]
width = 3
height = 3
$queue = []

def add_queue(dicts, dict)
  dicts2 = dicts.dup
  dicts2 << dict
  $queue << dicts2
end

while true do
  # ?§????
  panels = first_panels.dup
  z = panels.index(0)
  dicts = $queue.shift || []
  dicts.each do |d|
    case d
    when :u then panels[z], panels[z-3] = panels[z-3], panels[z]
    when :d then panels[z], panels[z+3] = panels[z+3], panels[z]
    when :l then panels[z], panels[z-1] = panels[z-1], panels[z]
    when :r then panels[z], panels[z+1] = panels[z+1], panels[z]
    end
    z = panels.index(0)
  end
  # ??????????????????
  if panels == target_panels
    puts dicts.size
    break
  end
  # ?¬??????¢?´¢?????????
  if z / width != 0 && dicts[-1] != :d
    add_queue(dicts, :u)
  end
  if z / width != height - 1 && dicts[-1] != :u
    add_queue(dicts, :d)
  end
  if z % width != 0 && dicts[-1] != :r
    add_queue(dicts, :l)
  end
  if z % width != width - 1 && dicts[-1] != :l
    add_queue(dicts, :r)
  end
end