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>

int V[1000000],dx[4]={-1,0,1,0},dy[4]={0,-1,0,1},head=0,tail=0;

struct P{
  int f[9];
  int space;
  int path;
};

struct P Q[1000000];

void enqueue(struct P a){
  int next=(tail+1)%1000000;
  Q[tail]=a;
  tail=next;
}

struct P dequeue(){
  struct P b;
  b=Q[head];
  head=(head+1)%1000000;
  return b;
}

int sort(struct P p){
  int i,j,k,cnt,a=0;
  for(i=0,k=1;i<9;k*=++i){
    for(j=0,cnt=0;j<i;j++){
      if(p.f[j]<p.f[i]){
	cnt++;
      }
    }
    a+=cnt*k;
  }
  return a;
}

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

int bfs(struct P s){
  int r,a,sx,sy,tx,ty;
  struct P u,v;
  s.path=0;
  enqueue(s);
  V[sort(s)]=1;
  while(head!=tail){
    u=dequeue();
    if(isTarget(u)==1){
      return u.path;
    }
    sx=u.space/3;
    sy=u.space%3;
    for(r=0;r<4;r++){
      tx=sx+dx[r];
      ty=sy+dy[r];
      if(tx<0||ty<0||tx>=3||ty>=3){
	continue;
      }
      v=u;
      a=v.f[u.space];
      v.f[u.space]=v.f[tx*3+ty];
      v.f[tx*3+ty]=a;
      v.space=tx*3+ty;
      if(V[sort(v)]!=1){
	V[sort(v)]=1;
	v.path++;
	enqueue(v);
      }
    }
  }
  return -1;
}

int main(){
  int i;
  struct P in;
  for(i=0;i<9;i++){
    scanf("%d",&in.f[i]);
    if(in.f[i]==0){
      in.f[i]=9;
      in.space=i;
    }
  }
  printf("%d\n",bfs(in));
  return 0;
}