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 MAX 362880
#define N 3
#define N2 9


typedef struct puzzle{
  int f[N2];
  int space;
  int path;
}PUZZLE;

static const int dx[4] = {-1, 0, 1, 0};
static const int dy[4] = {0, -1, 0, 1};

int V[MAX];

PUZZLE Q[MAX];
int head, tail;

void push(PUZZLE x){
  Q[tail] = x;
  tail = (tail+1)%MAX;
}

PUZZLE pop(){
  PUZZLE x;
  x = Q[head];
  head = (head+1)%MAX;
  return x;
}

int check(PUZZLE p){
  int i, j, fac, count, res = 0;
  for(i = 0, fac = 1; i < N2; fac*= ++i){
    for(j = 0, count = 0; j < i; j++){
      if(p.f[j] < p.f[i]) count++;
    }
    res += count*fac;
  }
  return res;
}

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

int bfs(PUZZLE s){
  int sx, sy, tx, ty, r, temp;
  PUZZLE u, v;

  s.path = 0;
  push(s);
  V[check(s)] = 1;

  while(head != tail){
    u = pop();

    if( isTarget(u))
      return u.path;

    sx = u.space / N;
    sy = u.space % N;

    for ( r = 0; r < 4; r++ ) {
      tx = sx + dx[r];
      ty = sy + dy[r];

      if(tx < 0 || ty < 0 || tx >= N || ty >= N)
	continue;
      
      v = u;
      temp = v.f[u.space];
      v.f[u.space] = v.f[tx * N + ty];
      v.f[tx * N + ty] = temp;

      v.space = tx * N + ty;

      if( !V[check(v)] ){
	V[check(v)] = 1;
	v.path++;
	push(v);
      }
    }
  }
  return -1;
}

int main(){
  int i, ans;
  PUZZLE in;

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

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

  return 0;
}