Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

8 Puzzle

The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.

In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.

1 3 0
4 2 5
7 8 6

You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).

1 2 3
4 5 6
7 8 0

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The $3 \times 3$ integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

There is a solution.

Sample Input

1 3 0
4 2 5
7 8 6

Sample Output

4

Solution in Ruby (judge verdict: Time Limit Exceeded)

# ???????????¢??¶?????????
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