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: Memory Limit Exceeded)

#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <map>
#include <queue>
#include <cmath>
using namespace std;
const int num = 16, ud[] = { -1, 0, 0, 1 }, lr[] = { 0, -1, 1, 0 }, nd = 4;
int md[num][num];
struct puzzle {
	int sp, p[num], mdp, cost;
	bool operator < (const puzzle &pu) const {
		for (int i = 0; i < num; i++) {
			if (p[i] == pu.p[i]) continue;
			return p[i] < pu.p[i];
		}
		return false;
	}
};
struct state {
	puzzle pu;
	int es;
	bool operator < (const state &s) const {
		//return pu.mdp + pu.cost > s.pu.mdp + s.pu.cost;
		return es > s.es;
	}
};
int astar(puzzle pz) {
	priority_queue<state> pq;
	int sum = 0;
	for (int i = 0; i < num; i++) {
		if (pz.p[i] == num) continue;
		sum += md[i][pz.p[i] - 1];
	}
	pz.mdp = sum;
	pz.cost = 0;
	map<puzzle, bool> m;
	puzzle u, v;
	state initial;
	initial.pu = pz;
	initial.es = pz.mdp;
	pq.push(initial);
	while (!pq.empty()) {
		state st = pq.top(); pq.pop();
		u = st.pu;
		if (!u.mdp) return u.cost;
		m[u] = true;
		int sx = u.sp / nd;
		int sy = u.sp % nd;
		for (int r = 0; r < nd; r++) {
			int tx = sx + ud[r];
			int ty = sy + lr[r];
			if (tx >= nd || tx < 0 || ty >= nd || ty < 0) continue;
			v = u;
			//v.mdp = p.mdp - md[tx * nd + ty][tmp.p[tx * nd + ty] - 1] + md[sx*nd + sy][tmp.p[tx * nd + ty] - 1];
			v.mdp -= md[tx * nd + ty][v.p[tx * nd + ty] - 1];
			v.mdp += md[sx*nd + sy][v.p[tx * nd + ty] - 1];
			swap(v.p[sx * nd + sy], v.p[tx * nd + ty]);
			v.sp = tx * nd + ty;
			if (!m[v]) {
				v.cost++;
				state news;
				news.pu = v;
				news.es = v.cost + v.mdp;
				pq.push(news);
			}
		}
	}
	return -1;
}

int main() {
	puzzle in;
	for (int i = 0; i < num; i++)
		for (int j = 0; j < num; j++)
			md[i][j] = abs(i / nd - j / nd) + abs(i%nd - j%nd);
	for (int i = 0; i < num; i++) {
		cin >> in.p[i];
		if (!in.p[i]) { in.sp = i;  in.p[i] = num; }
	}
	cout << astar(in) << endl;
	return 0;
}