![]() |
VOOZH | about |
Given a 4ร4 board with 15 tiles (every tile has one number from 1 to 15) and one empty space. The objective is to place the numbers on tiles in order using the empty space. We can slide four adjacent (left, right, above and below) tiles into the empty space. For example,
Here X marks the spot to where the elements can be shifted and the final configuration always remains the same the puzzle is solvable.
In general, for a given grid of width N, we can find out check if a N*N - 1 puzzle is solvable or not by following below simple rules :
What is an inversion here?
If we assume the tiles written out in a single row (1D Array) instead of being spread in N-rows (2D Array), a pair of tiles (a, b) form an inversion if a appears before b but a > b.
For above example, consider the tiles written out in a row, like this:
2 1 3 4 5 6 7 8 9 10 11 12 13 14 15 X
The above grid forms only 1 inversion i.e. (2, 1).
Illustration:
Below is a simple C++ program to check whether a given instance of 15 puzzle is solvable or not. The program is generic and can be extended to any grid width.
Solvable
Time Complexity : O(n2)
Space Complexity: O(n)
How does this works?
Fact 1: For a grid of odd width, all legal moves preserve the polarity (even or odd) of the number of inversions.
Proof of Fact 1
Fact 2: For a grid of even width, the following is invariant: (#inversions even) == (blank on odd row from bottom).
Example: Consider the move above. The number of inversions on the left is 49, and the blank is on an even row from the bottom. So the value of the invariant is "false == false", which is true. The number of inversions on the right is 48, because the 11 has lost two inversions, but the 14 has gained one. The blank is on an odd row from the bottom. So the value of the invariant is "true==true", which is still true.
Proof of Fact 2
Combining Fact 1 + Fact 2 = Fact 3:
Proof of fact 3:
Related Article:
How to check if an instance of 8 puzzle is solvable?
Source :
https://markryan.eu/teaching/modules04/java2/TilesSolvability.html