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 <stdlib.h>

#define N 3
#define N1 4
#define N2 9
#define N3 100

int puz[N][N];
int tmp[N][N];
int dx[N1]={0,1,0,-1};
int dy[N1]={1,0,-1,0};

void emp(int x[],int y[]) {
  int i,j;
  for(i=0;i<N;i++) {
    for(j=0;j<N;j++) {
      if(!puz[i][j]) {
        *x = j;
        *y = i;
        return;
      }
    }
  }
}

void swap(int a[],int b[]){
  int tmp;
  tmp=*a;
  *a=*b;
  *b=tmp;
}

int calsum(){
  int i,a,sum=0;
  for(i=0; i<N2; i++){
    a = puz[i/N][i%N];
    if(a){
      a--;
      sum+=abs((i/N)-(a/N))+abs((i%N)-(a%N));
    }
  }
  return sum;
}

int dfs(int x,int y,int p,int dep,const int lim){
  int i,h,nx,ny,res;
  h=calsum();
  if(h==0) return dep;
  if(dep+h>lim) return -1;
  for(i=0;i<N1;i++){
    nx=x+dx[i];
    ny=y+dy[i];
    if(~p && i==(p+2)%N2) continue;
    if(!(0<=nx && nx<N && 0<=ny && ny<N)) continue;
    swap(&puz[y][x],&puz[ny][nx]);
    res = dfs(nx,ny,i,dep+1,lim);
    if(~res) return res;
    swap(&puz[y][x],&puz[ny][nx]);
  }
  return -1;
}

int main() {
  int i,j,ans,x,y,l;
  for(i=0;i<N;i++){
    for(j=0;j<N;j++) scanf("%d",&puz[i][j]);
  }
  emp(&x,&y);
  for(l=0;l<N3;l++){
    for(i=0;i<N;i++){
      for(j=0;j<N;j++) tmp[i][j] = puz[i][j];
    }
    ans=dfs(x,y,-1,0,l);
    if(ans!=-1){
      printf("%d\n",ans);
      break;
    }
    for(i=0;i<N;i++){
      for(j=0;j<N;j++) puz[i][j] = tmp[i][j];
    }
    ans = -1;
    if(l==N3-1) printf("%d\n",ans);
  }
  return 0;
}