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>
#define N 4

int num(int,int,int,int);

int tum();
void rum(int *, int *);

int ma[N]={-1,0,1,0},lon[N]={0,-1,0,1};
int rin[N][N],sum;
int main(){
  int i,j,mizu,tani;
  for(i=0;i<4;i++){
    for(j=0;j<4;j++){
      scanf("%d",&rin[i][j]);
      if(rin[i][j]==0){
	
	mizu=j;
	tani=i;	
      }
    }
  }
  
  for(sum=0;;sum++){
    if(num(0,10,mizu,tani)==1) break;
  }
  printf("%d\n",sum);  
  return 0;
}
int  num(int a, int b, int c, int d){
  int i,xx,yy,ta;
  ta=tum();
  if(ta==0) return 1;
  if(a+ta>sum) return -1;
  
    for(i=0;i<4;i++){
      if(i-b==-2 || i-b==2) continue;
      xx=c+ma[i];
      yy=d+lon[i];
      if(xx<0 || yy<0 || xx>=4 || yy>=4) continue;
      rum(&rin[d][c],&rin[yy][xx]);
      
      if(num(a+1,i,xx,yy)==1) return 1;
      rum(&rin[d][c],&rin[yy][xx]);
      
    }
    return -1;
    
}



int tum(){
  int i,j,a=0;
  for(i=0;i<4;i++){
    for(j=0;j<4;j++){
      if(rin[i][j]==0) continue;
      a+=abs((rin[i][j]-1)/4-i)+abs((rin[i][j]-1)%4-j);
      
 
    }
  }
  return a;
}


void rum(int * xu, int *fan){  
  int c;
  c=*xu;
  *xu=*fan;
  *fan=c;
}