Post · 2 min read· pp. 809–810

15 Puzzle Game: Existence Of The Solution

This game is played on a 4×44 \times 4 board. On this board there are 1515 playing tiles numbered from 1 to 15. One cell is left empty (denoted by 0). You need to get the board to the position presented below by repeatedly moving one of the tiles to the free space:

1234567891011121314150\begin{matrix} 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8 \\ 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 0 \end{matrix}

The game "15 Puzzle” was created by Noyes Chapman in 1880.

Existence Of The Solution

Let's consider this problem: given a position on the board, determine whether a sequence of moves which leads to a solution exists.

Suppose we have some position on the board:

a1a2a3a4a5a6a7a8a9a10a11a12a13a14a15a16\begin{matrix} a_1 & a_2 & a_3 & a_4 \\ a_5 & a_6 & a_7 & a_8 \\ a_9 & a_{10} & a_{11} & a_{12} \\ a_{13} & a_{14} & a_{15} & a_{16} \end{matrix}

where one of the elements equals zero and indicates an empty cell az=0a_z = 0

Let’s consider the permutation:

a1a2...az−1az+1...a15a16a_1 a_2 ... a_{z-1} a_{z+1} ... a_{15} a_{16}

i.e. the permutation of numbers corresponding to the position on the board without a zero element

Let NN be the number of inversions in this permutation (i.e. the number of such elements aia_i and aja_j that i<ji < j, but ai>aja_i > a_j).

Suppose KK is an index of a row where the empty element is located (i.e. using our convention, K=(z−1)÷ 4+1K = (z - 1) \div \ 4 + 1).

Then, the solution exists iff N+KN + K is even.

Implementation

The algorithm above can be illustrated with the following program code:

text
int a[16];
for (int i=0; i<16; ++i)
    cin >> a[i];

int inv = 0;
for (int i=0; i<16; ++i)
    if (a[i])
        for (int j=0; j<i; ++j)
            if (a[j] > a[i])
                ++inv;
for (int i=0; i<16; ++i)
    if (a[i] == 0)
        inv += 1 + i / 4;

puts ((inv & 1) ? "No Solution" : "Solution Exists");

Proof

In 1879 Johnson proved that if N+KN + K is odd, then the solution doesn’t exist, and in the same year Story proved that all positions when N+KN + K is even have a solution.

However, all these proofs were quite complex.

In 1999 Archer proposed a much simpler proof (you can download his article here).

Practice Problems