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 Python3 (judge verdict: Wrong Answer)

# coding=utf-8
import heapq as hq

def next_board(board, space, prev):
    for nxt in adjacent[space]:
        if nxt == prev:
            continue
        b = board.copy()
        b[space], b[nxt] = b[nxt], 0
        yield b, nxt

def search(start):
    FORE = 1
    BACK = -1

    table = {}
    table[tuple(start)] = (FORE, 0)
    table[tuple(goal)] = (BACK, 0)

    heap = [(0, start, start.index(0), None, FORE), (0, goal, goal.index(0), None, BACK)]

    while heap:
        i, board, space, prev, direction = hq.heappop(heap)
        i += 1
        for b, nxt in next_board(board, space, prev):
            key = tuple(b)
            if key in table:
                if table[key][0] != direction:
                    return table[key][1] + i
            table[key] = (direction, i)
            hq.heappush(heap, (i, b, b.index(0), nxt, direction))

adjacent = (
    (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 = [1, 2, 3, 4, 5, 6, 7, 8, 0]
start = []

for _ in range(3):
    x = list(map(int, input().split()))
    start += x

print(search(start))