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 C (judge verdict: Memory Limit Exceeded)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char b[10];
  int step;
} Board;

int qlen=400000;

typedef enum { U, D, L, R } Direction;

typedef struct {
  int pos;
  Direction dir;
} Motion;

const Motion motion[9][5] =
  {{{1,L},{3,U},{-1}}, {{0,R},{2,L},{4,U},{-1}}, {{1,R},{5,U},{-1}},
   {{0,D},{4,L},{6,U},{-1}}, {{1,D},{5,L},{7,U},{3,R},{-1}},
   {{2,D},{8,U},{4,R},{-1}},
   {{3,D},{7,L},{-1}}, {{4,D},{8,L},{6,R},{-1}}, {{5,D},{7,R},{-1}}  };


int main()
{
  int i, k, n;
  int qhead=0;
  int qtail=0;
  Board board;
  fscanf(stdin, "%c %c %c\n", &board.b[0], &board.b[1], &board.b[2]);
  fscanf(stdin, "%c %c %c\n", &board.b[3], &board.b[4], &board.b[5]);
  fscanf(stdin, "%c %c %c\n", &board.b[6], &board.b[7], &board.b[8]);
  board.b[9]=0;
  short int *used = (short int*)malloc(sizeof(short int)*87654321);
  for (i=0; i<87654321; i++) used[i]=0;
  Board *Q = (Board*)malloc(sizeof(Board)*qlen);
  board.step=0;
  Q[qhead++] = board;
  
  while (qhead>qtail) {
    board = Q[qtail++ %qlen];
    
    if (strncmp(board.b, "123456780", 8)==0)   break;

    k=board.b[7];
    n=10;
    for (i=1; i<8; i++) {
      k += (board.b[7-i]-'0')*n;
      n*=10;
    }
    
    if ((used[k] & (1<<(board.b[8]-'0')))==(1<<(board.b[8]-'0'))) continue;
    used[k] |= (1<<(board.b[8]-'0'));
    
    int space = (int)(strchr(board.b, '0')-board.b);    
    for (i=0; motion[space][i].pos>=0; i++) {
      Board b = board;
      Motion m = motion[space][i];
      if (m.pos==0 && b.b[0]=='1') continue;
      if ((m.pos==1||m.pos==2) && b.b[0]=='1'&&b.b[1]=='2'&&b.b[2]=='3') continue;
      b.b[space] = b.b[m.pos];
      b.b[m.pos] = '0';
      b.step=board.step+1;
      Q[qhead++ %qlen] = b;
    }
  }
  printf("%d\n", board.step);
  return 0;
}