class EightPuzzle
  DX = [0, -1, 0, 1]
  DY = [-1, 0, 1, 0]
  TARGET = [1, 2, 3, 4, 5, 6, 7, 8, 0]

  class Puzzle
    attr_accessor :place, :sp, :cnt

    def initialize(place)
      @place = place
      @sp = place.index(0)
      @cnt = 0
    end

    def initialize_copy(obj)
      @place = obj.place.dup
      @sp = obj.sp
      @cnt = obj.cnt
    end
  end

  def initialize
    place = []
    3.times do
      place << gets.split.map(&:to_i)
    end
    place.flatten!
    @puz = Puzzle.new(place)
    @q = []
    @s = {}
  end

  def solve
    @q << @puz
    @s[@puz.place] = true

    while !@q.empty?
      puz = @q.shift
      return puz.cnt if puz.place == TARGET
      sx = puz.sp % 3
      sy = puz.sp / 3
      (0..3).each do |i|
        x = sx + DX[i]
        y = sy + DY[i]
        next if x < 0 || 2 < x || y < 0 || 2 < y
        v = puz.dup
        v.place[puz.sp], v.place[3 * y + x] = v.place[3 * y + x], v.place[puz.sp]
        v.sp = 3 * y + x
        unless @s[v.place]
          @s[v.place] = true
          v.cnt += 1
          @q << v
        end
      end
    end
  end
end

ep = EightPuzzle.new
puts ep.solve