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>
#define N 3
int suretu[N][N] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 0}};
int dx[] = { 0, 1, 0, -1 };
int dy[] = { -1, 0, 1, 0 };
int keisan(int f[N][N]) {
  int i,j;
    for (i=0;i<N;++i) {
        for (j=0;j<N;++j) {
            if(f[i][j] != suretu[i][j])
                return 0;
        }
    }
    return 1;
}
int jeep(int f[N][N], int x, int y, int v, int d, int l) {
  int i,j,res,nx,ny;
    if (keisan(f)) return d;
    if (d > l)return -1;
    for (i=0;i<4;++i) {
        nx=x+dx[i]; ny=y+dy[i];
        if (nx<0||nx>2||ny<0||ny>2||(i+2)%4==v)
            continue;
        f[y][x]=f[ny][nx]; f[ny][nx]=0;
        if((res=jeep(f, nx, ny, i, d + 1, l)) > 0)return res;
        f[ny][nx] = f[y][x];  f[y][x] = 0;
    }
    return -1;
}
int main() {
  int f[N][N], x, y,i,j,res;
    for (i=0; i< N; ++i) {
        for (j=0; j<N;++j) {
            scanf("%d",&f[i][j]);
            if(f[i][j]==0) {
                y=i;x=j;
            }
        }
    }
        for (i=1;i<50;++i) {
        if ((res=jeep(f,x,y,-1,0,i))>=0){
            break;
        }
    }
    printf("%d\n",res);
    return 0;
}