class Puzzle
  def initialize(state, direction, count=-1)
    @state = state
    @count = count
    @direction = direction
  end

  def calc_number
    nums = @state.dup
    @state.each_with_index do |x, i_x|
      @state[i_x..-1].each_with_index do |y, i_y|
        nums[i_x + i_y] -= 1 if y > x
      end
    end

    number = 0
    nums.each_with_index do |x, i_x|
      factorial = (nums.size - 1 - i_x).downto(1).inject(:*)
      number += factorial * x if factorial != nil
    end
    return number
  end

  def find_zero
    return @state.index(0)
  end

  def print_puzzle
    puts state[0..2].join(' ')
    puts state[3..5].join(' ')
    puts state[6..8].join(' ')
  end

  attr_accessor :state, :count, :direction
end

class Dictionary
  def initialize(num)
    @visited_dict = Array.new(num, 1)
    @count_dict = Array.new(num, 0)
  end

  attr_reader :visited_dict, :count_dict

  def visited?(index, direction)
    return @visited_dict[index] != 1 && @visited_dict[index] % direction == 0
  end

  def visit(puzzle)
    index = puzzle.calc_number
    direction = puzzle.direction
    count = puzzle.count
    @visited_dict[index] *= direction
    @count_dict[index] += count
  end

  def get_count(puzzle)
    return count_dict[puzzle.calc_number]
  end
end

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

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

FORWARD = 2
BACKWARD = 3

# main
init_state = []
3.times do 
  init_state.concat(gets.chomp.split.map(&:to_i))
end

queue = []
init_puzzle = Puzzle.new(init_state, FORWARD, 0)
goal_puzzle = Puzzle.new(GOAL_STATE, BACKWARD, 0)
queue << init_puzzle 
queue << goal_puzzle

dict = Dictionary.new(9.downto(1).inject(:*))
dict.visit(init_puzzle)
dict.visit(goal_puzzle)

while queue.size > 0 do
  puzzle = queue.shift
  index = puzzle.calc_number
  if dict.visited?(index, FORWARD) && dict.visited?(index, BACKWARD) then
    puts dict.count_dict[index] 
    break
  end

  zero_position = puzzle.find_zero
  swap_positions = SWAP_CHOICE[zero_position]

  swap_positions.each do |swap_pos|
    new_puzzle = Puzzle.new(puzzle.state.dup, 
                            puzzle.direction, 
                            puzzle.count + 1)
    new_puzzle.state[zero_position], new_puzzle.state[swap_pos] = 
      new_puzzle.state[swap_pos], new_puzzle.state[zero_position]
    next if dict.visited?(new_puzzle.calc_number, new_puzzle.direction)

    queue << new_puzzle
    dict.visit(new_puzzle)
  end
end