Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

15 Puzzle

The goal of the 15 puzzle problem is to complete pieces on $4 \times 4$ 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 15 as shown below.

1 2 3 4
6 7 8 0
5 10 11 12
9 13 14 15

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
9 10 11 12
13 14 15 0

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The $4 \times 4$ integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

The given puzzle is solvable in at most 45 steps.

Sample Input

1 2 3 4
6 7 8 0
5 10 11 12
9 13 14 15

Sample Output

8

Solution in C (judge verdict: Accepted)

#include <stdio.h>
#include <stdlib.h>

int answer=45;
int point;
int data1[16];

int nannyakonokannsuu(){
	int Ret=0;
	for(int i=0;i<16;i++){
		if(data1[i]!=15)Ret+=abs(i/4-data1[i]/4)+abs(i%4-data1[i]%4);
	}
	return Ret;
}

int swap(int i,int j){
	int t=data1[i];

	data1[i]=data1[j];
	data1[j]=t;
}

void find(int yokuwakarannatai,int move){
	int d=nannyakonokannsuu();
	if(move+d>answer)return;
	if(d==0){
		answer=move;
		return;
	}
	if(yokuwakarannatai!=1&&point>3  )swap(point,point-4),point-=4,find(0,move+1),point+=4,swap(point,point-4);
	if(yokuwakarannatai!=0&&point<12 )swap(point,point+4),point+=4,find(1,move+1),point-=4,swap(point,point+4);
	if(yokuwakarannatai!=3&&point%4>0)swap(point,point-1),point-=1,find(2,move+1),point+=1,swap(point,point-1);
	if(yokuwakarannatai!=2&&point%4<3)swap(point,point+1),point+=1,find(3,move+1),point-=1,swap(point,point+1);
}

int main(){
	for(int i=0;i<16;i++){
		int t;
		scanf("%d",&t);
		if(t)data1[i]=t-1;
		else{
			data1[i]=15;
			point=i;
		}
	}
	find(-1,0);
	printf("%d\n",answer);
}