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 kei(int,int,int,int);
int c[9];

int main(){
	int i,a;
	for(i=0;i<9;i++){
		scanf("%d",&c[i]);
		if(c[i]==0)a=i;
	}
	printf("%d\n",kei(a,0,10,1));
	return 0;
}

int kei(int a,int co,int b,int e){
	int min=999,sum=0,i,m;
	if((e==co || b==10) && a==8){	
		for(i=0;i<8;i++){
			if(c[i]!=i+1){
				sum++;
				break;
			}
		}
		if(sum==0)return co;
	}
	while(co<e){
	
		if((a+1)%3!=0 && b!=a+1){
			m=c[a+1];
			c[a+1]=c[a];
			c[a]=m;
			m=kei(a+1,co+1,a,e);
			if(min>m){
				min=m;
				break;
			}
			m=c[a];
			c[a]=c[a+1];
			c[a+1]=m;
		}
		if((a-1)%3!=2 && a!=0 && b!=a-1){
			m=c[a];
			c[a]=c[a-1];
			c[a-1]=m;
			m=kei(a-1,co+1,a,e);
			if(min>m){
				min=m;
				break;
			}
			m=c[a];
			c[a]=c[a-1];
			c[a-1]=m;
		}
		if(a-3>=0 && b!=a-3){
			m=c[a];
			c[a]=c[a-3];
			c[a-3]=m;
			m=kei(a-3,co+1,a,e);
			if(min>m){
				min=m;
				break;
			}
			m=c[a];
			c[a]=c[a-3];
			c[a-3]=m;
		}
		if(a+3<9 && b!=a+3){
			m=c[a];
			c[a]=c[a+3];
			c[a+3]=m;
			m=kei(a+3,co+1,a,e);
			if(min>m){
				min=m;
				break;
			}
			m=c[a];
			c[a]=c[a+3];
			c[a+3]=m;
		}
		if(b==10)e++;		
		else return min;
	}
	return min;
}