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 ans=45;
int p;
int a[16];
int L1dist(){
	int ret=0;
	for(int i=0;i<16;i++)if(a[i]!=15)ret+=abs(i/4-a[i]/4)+abs(i%4-a[i]%4);
	return ret;
}
int swap(int i,int j){int t=a[i];a[i]=a[j];a[j]=t;}

void f(int pre,int movs){
	int d=L1dist();
	if(movs+d>ans)return;
	if(d==0){
		ans=movs;
		return;
	}
	if(pre!=1&&p>3  )swap(p,p-4),p-=4,f(0,movs+1),p+=4,swap(p,p-4);
	if(pre!=0&&p<12 )swap(p,p+4),p+=4,f(1,movs+1),p-=4,swap(p,p+4);
	if(pre!=3&&p%4>0)swap(p,p-1),p-=1,f(2,movs+1),p+=1,swap(p,p-1);
	if(pre!=2&&p%4<3)swap(p,p+1),p+=1,f(3,movs+1),p-=1,swap(p,p+1);
}

int main(){
	for(int i=0;i<16;i++){
		int t;
		scanf("%d",&t);
		if(t)a[i]=t-1;
		else{
			a[i]=15;
			p=i;
		}
	}
	f(-1,0);
	printf("%d\n",ans);
}