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

int puzz[N][N];
int dy[4]={1,0,-1,0};
int dx[4]={0,1,0,-1};

int huri(){

  int x,y ,i,j,sum=0;

  for(i=0;i<N;i++){
    for(j=0;j<N;j++){
      if(puzz[i][j] == 0)continue;

      x=(puzz[i][j]-1)%N-j;
      y=(puzz[i][j]-1)/N-i;
      x=abs(x);
      y=abs(y);
      
      sum+=x;
      sum+=y;
    }
  }
  return sum;
}

int DFS(int iof0,int jof0,int lim,int dpt){

  int i,j,h,x,y,tmp,ans=-1;

  h = huri();
  if(h == 0) return dpt;
  if(h+dpt > lim) return -1;

  for(i=0;i<4;i++){
    x = iof0 + dx[i];
    y = jof0 + dy[i];

    if(x >= N || x < 0) continue;
    if(y >= N || y < 0) continue;

    tmp = puzz[x][y];
    puzz[x][y] = puzz[iof0][jof0];
    puzz[iof0][jof0] = tmp;

    ans = DFS(x,y,lim,dpt+1);

    if(ans != -1) return ans;
    tmp = puzz[x][y];
    puzz[x][y] = puzz[iof0][jof0];
    puzz[iof0][jof0] = tmp;
  }
  return -1;
}

int main(){

  int i,j,iof0,jof0,ans;

  for(i=0;i<N;i++){
    for(j=0;j<N;j++){
      scanf("%d",&puzz[i][j]);
      if(puzz[i][j] == 0){
	iof0 = i;
	jof0 = j;
      }
    }
  }

  for(i=1;i<101;i++){
    ans = DFS(iof0,jof0,i,0);
    if(ans != -1) {
      printf("%d\n",ans);
      break;
    }
  }

  return 0;
}