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

start_panels = [1, 2, 3, 4, 5, 6, 7, 8, 0]
width = 3
height = 3
$queue = [[true, []], [false, []]]
forward_cache = {}
backward_cache = {}

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

while true do
  # ?§????
  q = $queue.shift
  is_forward, dicts = q[0], q[1]
  if is_forward
    panels = start_panels.dup
  else
    panels = end_panels.dup
  end
  z = panels.index(0)
  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
#pp dicts
  # ??????????????????
  if is_forward && backward_cache.key?(panels)
    puts dicts.size + backward_cache[panels].size
    break
  elsif !is_forward && forward_cache.key?(panels)
    puts dicts.size + forward_cache[panels].size
    break
  end
  if is_forward
    if !forward_cache.key?(panels) || forward_cache[panels].size > dicts.size
      forward_cache[panels] = dicts
    end
  else
    if !backward_cache.key?(panels) || backward_cache[panels].size > dicts.size
      backward_cache[panels] = dicts
    end
  end

  # ?¬??????¢?´¢?????????
  if z / width != 0 \
     && dicts[-1] != :d
     # && dicts[-3, 3] != [:l, :d, :r] \
     # && dicts[-3, 3] != [:r, :d, :l]
    add_queue(is_forward, dicts, :u)
  end
  if z / width != height - 1 \
     && dicts[-1] != :u
     # && dicts[-3, 3] != [:l, :u, :r] \
     # && dicts[-3, 3] != [:r, :u, :l]
    add_queue(is_forward, dicts, :d)
  end
  if z % width != 0 \
     && dicts[-1] != :r
     # && dicts[-3, 3] != [:u, :r, :d] \
     # && dicts[-3, 3] != [:d, :r, :u]
    add_queue(is_forward, dicts, :l)
  end
  if z % width != width - 1 \
     && dicts[-1] != :l
     # && dicts[-3, 3] != [:u, :l, :d] \
     # && dicts[-3, 3] != [:d, :l, :u]
    add_queue(is_forward, dicts, :r)
  end
end