Eight tiles and one gap
Eight numbered tiles sit in a 3×3 frame with one empty square. You slide tiles into the hole, trying to get back to 1 2 3 / 4 5 6 / 7 8. Sharper question: what is the fewest number of moves that will do it? And sharper still: can every scramble be solved at all?
That second question caused a real uproar more than 140 years ago. The 4×4 version, the 15 puzzle, became a craze in the United States in 1880, and people even offered cash rewards for solutions. But some arrangements can never be solved, no matter what you do, and a mathematical proof of that was already in print when the craze was just getting started.
You play by feel; a computer has no feel. The honest first approach is "try everything." How much is everything? There are ways to place eight tiles and a hole in nine squares. For the 15 puzzle the count becomes , about : at a million arrangements per second, almost eight months. So the real question here is how a computer can find the shortest solution, guaranteed, without trying everything. The trick is a good guess.
Redraw the puzzle as a network
Make every arrangement of the board a dot, and connect two dots with a line if one move takes you from one to the other. The puzzle becomes a gigantic network, a graph, and solving it means finding the shortest path from the start dot to the goal dot. It is like a journey planner on a subway map, with boards for stations and moves for tracks. The analogy breaks in one important place: a journey planner knows the whole map, but the computer does not have this network to begin with.
So the computer builds it as it goes. From the initial board it makes every board reachable in one move, then the boards reachable from those, and so on. Making all the neighbors of a board is called expanding it. Boards waiting to be expanded sit in the open list; boards already expanded are recorded in a closed set.
Here is the lovely part: the search methods differ in exactly one thing, namely which waiting board they take out next. Breadth-first search, or BFS, takes the oldest one, the way a queue works, so it looks at all boards 0 moves away, then 1, then 2, layer by layer; the first solution it meets is a shortest one, but the layers get fatter and fatter. A\*, pronounced "A-star," takes the board with the smallest , where is the number of moves made so far and is an estimate of the moves still needed. Greedy best-first search looks only at , grabbing whatever seems closest to the goal.
Each of these search methods has an origin story. Konrad Zuse described breadth-first search in 1945 in a doctoral thesis that was rejected, and the work was not published until 1972. In 1959 Edward Moore reinvented it to find the shortest way out of a maze, and in 1961 C. Y. Lee turned it into a method for routing the wires on circuit boards.
In 1956 Edsger Dijkstra, at the Mathematical Centre in Amsterdam, wanted to show off the new ARMAC computer with a problem that people who knew nothing about computers could understand: the shortest route on a simplified map of 64 Dutch cities. By his own later account, he designed the method in about twenty minutes while sitting on a café terrace with his fiancée after shopping, and he felt that doing it without pencil and paper was one reason it came out so clean. He published it in 1959.
A thought experiment: suppose is always 0. Then A* just picks the smallest , which is basically BFS. Now suppose is perfect, always equal to the true number of moves left. Then A* walks straight along a shortest path with hardly a detour. Real estimates live in between, and their quality decides how much work the search does.
An optimistic estimate
Two estimates are popular for the 8 puzzle. The misplaced-tiles count is simply the number of tiles not where they belong. The Manhattan distance adds up, for every tile, how many rows and columns it is away from its home square.
Neither ever overestimates the true number of moves left, . For Manhattan distance the reason is short and sweet: one move shifts one tile by one square, so the total drops by at most 1 per move. Every misplaced tile must move at least once, so that count is safe too. An estimate with is called admissible. You could also call it optimistic. An estimate that exaggerates can make A* put off boards that are actually on the shortcut and hand you a solution that is not the shortest. And since every misplaced tile is at least one square from home, Manhattan distance is always at least the misplaced count: still admissible, but closer to the truth.
Road maps even have their own admissible estimate: the straight-line distance to your destination. A road can never be shorter than a straight line, so it never overestimates, the same role Manhattan distance plays in the puzzle.
Why the first answer is the shortest
Why does admissibility guarantee a shortest solution? Suppose A* pulls out a solution of length while a shorter one of length exists. Somewhere on that shorter path a board is still waiting in the open list, with
A* always takes the smallest first, so it should have taken before the longer solution. Contradiction!
Both estimates also change by at most 1 per move, which makes them consistent. In symbols, if one move takes board to board , then , and so
Along any path, never goes down. Since A* takes boards in order of increasing , the first time it takes out a board it has reached it by a shortest route, and it never needs to expand that board again. A careful proof takes a little more work, but this is the heart of it. That is exactly what the closed set relies on; without one, the same board gets expanded again and again along different routes.
A* was born in the late 1960s at the Stanford Research Institute, known as SRI, for Shakey, a mobile robot meant to plan its own actions. Nils Nilsson first proposed a method that chose the next step by the estimate alone, which is the greedy search in this simulation. Bertram Raphael suggested adding the distance already traveled, , and scoring by , and Peter Hart worked out the conditions we now call admissibility and consistency. Their 1968 paper even proved that, with a consistent estimate, no algorithm of the same kind using the same estimate can expand fewer nodes than A. A "correction" a few years later claimed consistency was not needed, but in 1985 Rina Dechter and Judea Pearl showed that the correction was the mistake. Even plausible claims get checked again. That same year Richard Korf used IDA\, a memory-saving variant, to solve random 15 puzzles optimally, and by the end of the 1990s it had been confirmed that every 15-puzzle position can be solved in at most 80 moves.
When a map app plans your route, when an enemy in a video game chases you around a wall, when a warehouse robot heads for a shelf without bumping into anything, a shortest-path search is running underneath. In games, A* is the standard tool. A road network has millions of intersections, so map services usually precompute shortcut information and use refined methods, but at the bottom lies the same idea as Dijkstra's and A*'s: expand outward from what is surely closest.
It also works where you can't see it. On the Internet, routers use Dijkstra's method to work out routes in protocols such as OSPF, and descendants of Lee's method have long been used to route the wiring of circuit boards and chips automatically.
Better containers, and an explosion that won't go away
Now count the work. Scanning an open list of boards for the smallest costs comparisons every time. A binary heap, a tree-shaped container, needs about . Why ? A binary heap is a tree in which every parent has two children, and it keeps just one promise: a parent's is never larger than its children's. So the board with the smallest always sits at the root. Each level down holds twice as many boards as the one above, so a tree of boards is only about levels tall. Adding a board at the bottom and swapping it upward past larger parents, or refilling the root after taking the smallest out, takes about one comparison per level. For , that is ten thousand versus about fourteen.
The puzzle is also a lesson in algorithms and data structures. One problem can take orders of magnitude more or less work depending on the method, and on whether you choose a queue, a priority queue or a set to hold the waiting boards. And it has relatives in this collection: the Tower of Hanoi and Recursion builds a shortest move sequence by recursion, while Graph 3-Coloring backs up from dead ends. All three look at a problem as states and moves.
No cleverness makes the explosion go away completely, though. For the version of the puzzle, finding a shortest solution was shown in 1986 to be NP-hard: no method is known whose work grows only like a power of , and most computer scientists believe none exists. Even computers meet problems that brute force cannot bully. That is precisely why good estimates, which cut down how much has to be searched, are worth so much.
Boards that can never be solved
Finally, back to the opening question: can every board be solved? Take the board with just 7 and 8 swapped, 1 2 3 / 4 5 6 / 8 7. Can it be fixed? No need to try hundreds of thousands of boards; we can settle it by counting. Read the tiles left to right, top to bottom, skipping the hole, and count the pairs where a bigger number comes before a smaller one: the inversion count. A sideways move does not change the reading order. An up-or-down move makes one tile jump over two others. Its order relative to each of those two flips, and each flip changes the count by +1 or −1, so the total change is −2, 0 or +2. Its evenness never changes! The goal has zero inversions, so a board with an odd count can never be solved. It is also true, though harder to prove, that every even board can be. The board with 7 and 8 swapped has one inversion, so it can never be solved; the 14–15 swap on the 4×4 board fails for the same kind of reason once the row of the hole is counted too. That is why exactly half the boards, , are reachable. A full search in this simulation shows that the farthest of them needs 31 moves, and only two boards are that far away.
The counting you meet in mathematics is right here: is just the number of permutations, and the evenness of the inversion count is what mathematicians call the parity of a permutation; every swap of two tiles flips it.
Those unsolvable boards come with a lively history.
The 15 puzzle is credited to Noyes Chapman, a postmaster in Canastota, New York, who is said to have shown friends an early version around 1874. It traveled to Hartford, Connecticut, where students at the American School for the Deaf began making it, and in December 1879 the Boston woodworker Matthias Rice started selling it. In 1880 the whole country went mad for it; in late January a dentist in Worcester, Massachusetts, offered a reward for a solution. Chapman applied for a patent in February, but it was turned down, probably because an earlier patent was too similar.
The famous puzzle-maker Sam Loyd claimed from 1891 until his death in 1911 that he had invented it, and he publicized a 1,000-dollar prize for anyone who could fix a board with only the 14 and 15 swapped. But a detailed history published in 2006 concluded that Loyd had nothing to do with the invention or the original craze. And the 14–15 swap can never be solved.
The proof had appeared in 1879 in the American Journal of Mathematics, founded only the year before, as two short notes: William Johnson showed that the arrangements with an odd permutation can never be reached, and William Story showed that all the even ones can. That style of argument, finding a quantity that no move can change and using it to prove something impossible, is still one of the basic weapons of mathematics.
Using an unchangeable quantity to rule things out is very much like a conservation law in physics. Once you know energy is conserved, you can say that no machine will keep running forever with nothing put in, without even looking at how it is built. The parity of the inversion count is the puzzle's conserved quantity. The 3×3×3 rotating-cube puzzle has a similar parity rule: a cube with just two pieces swapped can't be reached without taking it apart.
Watch the search yourself
- The opening board needs 18 moves at best. Press 🔍 Start search at the top of the panel. Watch "Board just expanded" with its g, h and f, and the row of "Next candidates" sorted by f. Use Pause and Step in the toolbar to check that the smallest f really is chosen.
- Predict first: how many times more boards will BFS expand than A* with Manhattan distance? Write down a guess, then press Compare five methods. On the opening board, BFS expands 24,433 boards and A* with Manhattan distance 154.
- Set Method to "Breadth-first search (BFS)", move the Search speed slider to the right and press 🔍 Start search again. Compare its chart "Boards expanded at each depth g" with the one for A*.
- In the comparison, look at the Greedy row. It is quick, so why is its solution not the shortest? Look also at the comparison count in the "No closed set" row.
- Press Swap two tiles (unsolvable board), or press Shuffle tiles a few times, until the line under the board says "unsolvable", then press ⚡ Solve at once. Where does the search stop, and why that number?
- Set Size to "4×4 (15-puzzle)", raise Number of random moves, and press Scramble and ⚡ Solve at once each time. When does the search hit its node limit?
Honest warning: the search is slowed to a few dozen boards per second; the real times appear in milliseconds in the comparison chart.
What a good estimate buys
Solving the puzzle means finding a shortest path in a network of boards. BFS, A\* and greedy search differ only in which waiting board they expand next. If the estimate never exceeds the true distance, A\* finds a shortest solution, and the better the estimate, the less work. A closed set and a binary heap cut the work by orders of magnitude, and the parity of the inversion count tells you whether a board can be solved at all.
A parity proof written as a craze began, search methods grown from mazes, circuit wiring and a robot that had to plan its route: they all lead to the map app in your pocket. To take away: can you invent an estimate closer to the truth than Manhattan distance that never overestimates? If it is slow to compute, is it still a bargain?
Sources and further reading
The facts in this article were checked mainly against the following.
- W. W. Johnson and W. E. Story, "Notes on the '15' Puzzle," American Journal of Mathematics, 1879: Johnson's proof that half the arrangements are impossible, and Story's that the rest are possible
- MacTutor, "James Joseph Sylvester" (University of St Andrews): the founding of the American Journal of Mathematics in 1878
- Wolfram MathWorld, "15 Puzzle": the 2006 historical research showing that Loyd did not invent the puzzle
- E. W. Dijkstra, "A note on two problems in connexion with graphs," Numerische Mathematik, 1959
- P. L. Frana and T. J. Misa, "An interview with Edsger W. Dijkstra," Communications of the ACM, 2010: his recollection of the twenty-minute invention in 1956
- P. E. Hart, N. J. Nilsson and B. Raphael, "A Formal Basis for the Heuristic Determination of Minimum Cost Paths," IEEE Transactions on Systems Science and Cybernetics, 1968
- R. Dechter and J. Pearl, "Generalized best-first search strategies and the optimality of A*," Journal of the ACM, 1985
- C. Y. Lee, "An Algorithm for Path Connections and Its Applications," IRE Transactions on Electronic Computers, 1961
- R. E. Korf, "Depth-first iterative-deepening: An optimal admissible tree search," Artificial Intelligence, 1985
- RFC 2328, "OSPF Version 2" (IETF, 1998)
Further reading (encyclopedias):
- Wikipedia, "15 puzzle": Chapman, the 1880 craze, the 80-move maximum, NP-hardness
- Wikipedia, "Breadth-first search": Zuse, Moore and Lee
- Wikipedia, "Dijkstra's algorithm"
- Wikipedia, "A* search algorithm": Shakey, and the roles of Nilsson, Raphael and Hart