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>
#define N 4
#define MAX 15
typedef struct{
    int A[N][N];
}Pazzle;
Pazzle P;
int d_x[4]={0,1,0,-1};
int d_y[4]={1,0,-1,0};

void swap(int *A,int *B){
 int hoge;
 hoge=*A;
 *A=*B;
 *B=hoge;
 
 
}

int check(Pazzle P){
    int sum=0,i,j,hy,hx;
    for(i=0;i<N;i++){
 
    for(j=0;j<N;j++){
        if(P.A[i][j]==0)
        continue;
        hy=(P.A[i][j]-1)/N-i;
        hx=(P.A[i][j]-1)%N-j;
        if(hy<0)
        sum-=hy;
        else
        sum+=hy;
        if(hx<0)
        sum-=hx;
        else
        sum+=hx;
 
 
}
}
 
return sum;
}

int dfs(int x,int y,int max,int cnt,int m){
         int i;
  int heau;
  int x_0,y_0;
  int ans=-1;   
  heau=check(P);
  if(heau==0) return cnt;
  if(cnt+heau>max) return -1; 
  for(i=0;i<4;i++){
    x_0=x+d_x[i];
    y_0=y+d_y[i];      
   
    if((m!=-1&&i==(m+2)%4)||!(0<=x_0 && x_0<N && 0<=y_0 && y_0<N)) continue;    
    swap(&P.A[y][x],&P.A[y_0][x_0]);
    ans=dfs(x_0,y_0,max,cnt+1,i);
    if(ans!=-1) return ans;       
     swap(&P.A[y][x],&P.A[y_0][x_0]);
  }   
  return -1;
}

int main(void){
    Pazzle t_P;
    int  i,j,ans;
    int x0,y0;

    for(i=0;i<N;i++){
        for(j=0;j<N;j++){
            scanf("%d",&P.A[i][j]);
            if(P.A[i][j]==0){
                x0=j;
                y0=i;
                
            }
            
        }
    }
    t_P=P;
    for(i=1;i<46;i++){
        P=t_P;
    ans=dfs(x0,y0,i,0,-1);
    if(ans!=-1){printf("%d\n",ans); break;}
    }
    return 0;
}