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: Accepted)

require 'set'

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

R = [0, 0, 0, 1, 1, 1, 2, 2, 2]
C = [0, 1, 2, 0, 1, 2, 0, 1, 2]

Factorials = (1...9).each_with_object([1]){ |i, arr| arr << arr[-1] * i }.reverse

def min_heapify(x = 1)
  l = 2*x
  r = 2*x+1
  if l <= $n && $heap[l][0] < $heap[x][0]
    minimum = l
  else
    minimum = x
  end
  if r <= $n && $heap[r][0] < $heap[minimum][0]
    minimum = r
  end
  if minimum != x
    $heap[x], $heap[minimum] = $heap[minimum], $heap[x]
    min_heapify(minimum)
  end
end

def extract
  key = $heap[1]
  $heap[1] = $heap[$n]
  $n -= 1
  min_heapify
  key
end

def insert(key)
  $n += 1
  $heap[$n] = key
  i = $n
  while i > 1 && $heap[i/2][0] > $heap[i][0]
    $heap[i], $heap[i/2] = $heap[i/2], $heap[i]
    i /= 2
  end
end

def create_hash(brd)
  b = brd.dup
  9.times do |i|
    (i+1...9).each do |j|
      b[j] -= 1 if b[i] < b[j]
    end
  end
  9.times.reduce(0){ |sum, i| sum += b[i] * Factorials[i] }
end

def dehash(key)
  brd = 9.times.map { |i| d, key = key.divmod(Factorials[i]); d }
  8.downto(0) do |i|
    (i+1...9).each do |j|
      brd[j] += 1 if brd[j] >= brd[i]
    end
  end
  brd
end

def judge(brd, c)
  ret = c
  9.times do |i|
    if brd[i] > 0
      [R, C].each do |a|
        ret += (a[i] - a[brd[i] - 1]).abs
      end
    end
  end
  ret
end

Goal = create_hash([1,2,3,4,5,6,7,8,0])

brd = 3.times.map{ gets.split.map(&:to_i) }.flatten
$heap = []
$n = 0
insert [judge(brd, 0), k = create_hash(brd), 0]
set = Set.new([])
set.add(k)
while $n > 0
  val, key, cnt = extract
  if val == cnt
    p cnt
    break
  end
  b = dehash(key)
  n = b.index(0)
  Move[n].each do |m|
    b[n], b[m] = b[m], b[n]
    k = create_hash(b)
    unless set.include?(k)
      set.add(k)
      insert [judge(b, cnt+1), k, cnt + 1]
    end
    b[n], b[m] = b[m], b[n]
  end
end