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

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

#define N 3
#define N2 9
#define TRUE 1
#define FALSE 0
#define MAX 500000

int V[MAX];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, -1, 0, 1};

void swap(int x, int y){/*入れ替えます*/
  int z = x;
  x = y;
  y = z;
}

struct Puzzle{/*構造体の宣言*/
  int f[N2];
  int space;
  int path;
};

struct Puzzle Q[MAX];
int head = 0, tail = 0;

void enqueue(struct Puzzle x){/* Q[tail] に x を代入し、tail を１つ増やします。 */
  int next = (tail+1)%MAX;  
  Q[tail] = x;
  tail = next;
}

struct Puzzle dequeue(){/* Q[head] の値を返し、head を１つ増やします。  */
  struct Puzzle t; 
  t = Q[head];
  head = (head+1)%MAX;
  return t;
}

int sort(struct Puzzle p){
  int i, j, key, count, n = 0;
  for(i = 0, key = 1; i < N2; key *= ++i){
    for(j = 0, count = 0; j < i; j++){
      if(p.f[j] < p.f[i])count++;
    }
    n += count * key;
  }
  return n;
}

int isTarget(struct Puzzle p){
  for(int i = 0; i < N2; i++)if(p.f[i] != (i+1))return FALSE;
  return TRUE;
}

int bfs(struct Puzzle s){
  struct Puzzle u, v;
  s.path = FALSE;
  enqueue(s);
  V[sort(s)] = TRUE;
  

  while(head != tail){ 
    u = dequeue();
    if(isTarget(u) == TRUE)return u.path;
    int sx = u.space / N;
    int sy = u.space % N;
    for(int r = 0; r < 4; r++){
      int tx = sx + dx[r];
      int ty = sy + dy[r];
      if(tx < 0 || ty < 0 || tx >= N || ty >= N)continue;
      v = u;
      int num = v.f[u.space];
      v.f[u.space] = v.f[tx * N + ty];
      v.f[tx * N + ty] = num;
      v.space = tx * N + ty;
      if(V[sort(v)] != TRUE){
	V[sort(v)] = TRUE;
	v.path++;
	enqueue(v);
      }
    }
  }

  return -1;
}

int main(){
  struct Puzzle in;

  for(int i = 0; i < N2; i++){
    scanf("%d",&in.f[i]);
    if(in.f[i] == 0){
      in.f[i] = N2;
      in.space = i;
    }
  }

  int ans = bfs(in);
  printf("%d\n",ans);

  return 0;
}