How A* uses Manhattan distance to solve the 8-puzzle
A* solves the 8-puzzle by searching boards in order of estimated total cost: the moves already made, plus a Manhattan-distance guess for the work still left. When that guess never overshoots, the first path A* reaches the goal on is a shortest path.
The rest of this page walks through that method, the solvability test you should run before any search, and a short Python example. When you want to see a shortest 3×3 path on a board of your own, this site's numbered 3×3 and 4×4 solver will play the moves one at a time.
What A* does on the 8-puzzle
The 8-puzzle is a 3×3 board with tiles 1 through 8 and one blank. A legal move slides a tile that sits next to the blank into the empty square. The usual goal, and the one used on this site, is tiles in reading order with the blank in the bottom-right corner: 1 2 3 / 4 5 6 / 7 8 0.
A* keeps a frontier of boards it has reached. Each board has two numbers: g, the number of slides already used to get there, and h, a heuristic estimate of how many slides are still needed. The algorithm always expands the board with the smallest f = g + h. It also remembers boards it has already finished with, so it does not expand the same arrangement twice.
That is the whole control loop. There is no special 8-puzzle rule inside A* itself. What makes the search practical — and what makes the first solution shortest — is the heuristic, which on this page is Manhattan distance with weight 1.
This walk-through is for someone learning the algorithm, or writing a course solver, who wants a method they can follow on paper and then run. If you only need a path for a board in front of you, enter it in the solver rather than coding first.
Why the search is finite
A 3×3 board has 9! = 362,880 ways to place the eight tiles and the blank, and only half of those arrangements can reach the goal by sliding. That reachable half is 181,440 boards, so a correctly written search cannot wander forever. It will either find the goal or exhaust the reachable set.
Manhattan distance as the heuristic
Manhattan distance for the 8-puzzle is the sum, over every numbered tile, of how many rows plus how many columns that tile sits away from its goal square. The blank is left out of the sum. Each slide moves one tile by one square, so a tile that is three squares away in this sense still needs at least three slides of its own.
Because the sum only counts those unavoidable steps, Manhattan distance never claims that a board is closer to the goal than it really is. In the language of A*, the heuristic is admissible. When h is admissible and A* expands the lowest f first, the first time the goal is selected it has been reached in the fewest slides possible.
A weaker alternative, often taught alongside this one, is the misplaced-tile count: how many numbered tiles are not yet in their goal squares. That number is also admissible, but it is a looser lower bound, so A* usually expands many more boards before it finishes.
If you want a demanding test case after the method is clear, the two 8-puzzle boards that take 31 moves are the longest shortest paths on the 3×3.
Why Manhattan distance does not overshoot
Suppose tile 8 is two rows and one column away from its goal. It must move at least three times, because one slide changes only one of those coordinates, and no other tile’s motion can reduce that minimum for tile 8. Adding the same minimum for every other numbered tile still does not over-count, because a single slide advances only one tile. The sum is therefore a safe underestimate of the remaining work.
A solvability check comes first
Before A* runs on an 8-puzzle, check whether the start board can reach the goal at all. If it cannot, no search will help, and you should return that answer instead of looking for a path.
The test for a 3×3, with the goal above, is the inversion count. Read the eight numbered tiles in order, skipping the blank, and count every pair in which a larger number appears before a smaller one. If that count is even, the board is solvable; if it is odd, it is not. A single slide never changes this even/odd class, which is why a legal shuffle stays solvable and a manual swap of two tiles can make the board impossible.
The same idea, with the blank’s row included, is what you use on a 4×4. The famous case of two tiles swapped in an otherwise finished 15-puzzle is why a 14-15 swap cannot be solved by sliding.
Even and odd inversion counts
A finished board has inversion count 0, which is even. Swapping 7 and 8 on that finished board, and leaving the blank in the corner, produces exactly one inversion. That position is odd, and A* should not be asked to solve it. The function in the Python section below returns no path in that case, rather than searching until the frontier is empty.
A Python 8-puzzle solver with A*
The example below is a compact 8-puzzle solver in Python. It uses the inversion test, Manhattan distance, and A* with f = g + h. The return value is the sequence of tiles that slide into the blank, which matches how this site’s solver highlights each move. Boards are written left to right, top to bottom, with 0 for the blank.
import heapq
GOAL = (1, 2, 3, 4, 5, 6, 7, 8, 0)
def manhattan(board):
distance = 0
for index, tile in enumerate(board):
if tile == 0:
continue
goal_index = tile - 1
distance += abs(index // 3 - goal_index // 3) + abs(index % 3 - goal_index % 3)
return distance
def inversion_count(board):
tiles = [tile for tile in board if tile != 0]
count = 0
for i, a in enumerate(tiles):
for b in tiles[i + 1:]:
if a > b:
count += 1
return count
def is_solvable(board):
return inversion_count(board) % 2 == 0
def neighbors(board):
blank = board.index(0)
row, col = divmod(blank, 3)
result = []
for d_row, d_col in ((-1, 0), (1, 0), (0, -1), (0, 1)):
n_row, n_col = row + d_row, col + d_col
if 0 <= n_row < 3 and 0 <= n_col < 3:
swap_with = n_row * 3 + n_col
new_board = list(board)
tile = new_board[swap_with]
new_board[blank], new_board[swap_with] = new_board[swap_with], new_board[blank]
result.append((tuple(new_board), tile))
return result
def astar(start):
start = tuple(start)
if not is_solvable(start):
return None
came_from = {start: (None, None)}
g_score = {start: 0}
heap = [(manhattan(start), 0, start)]
seen = set()
while heap:
_, g, node = heapq.heappop(heap)
if node in seen:
continue
seen.add(node)
if node == GOAL:
tiles = []
current = node
while came_from[current][0] is not None:
previous, tile = came_from[current]
tiles.append(tile)
current = previous
tiles.reverse()
return tiles
for nxt, tile in neighbors(node):
tentative = g + 1
if tentative < g_score.get(nxt, float("inf")):
g_score[nxt] = tentative
came_from[nxt] = (node, tile)
heapq.heappush(heap, (tentative + manhattan(nxt), tentative, nxt))
return None
board = (1, 2, 3, 4, 5, 6, 7, 0, 8)
print(astar(board))On that one-move board, the printed list is [8]: tile 8 slides down into the blank and the puzzle is finished. For an unsolvable start such as (1, 2, 3, 4, 5, 6, 8, 7, 0), astar returns None.
This example is for the 8-puzzle only. The 15-puzzle has a much larger space, and a shortest-path search needs a stronger design than the listing above. If you already have a 3×3 path from the code, you can type the same start board into the on-site solver and step through a shortest path there.
To try a 3×3 game rather than a typed-in board, play a 3×3 slide puzzle on the homepage.
How to read the output
Each number in the list is the tile that moves on that step, not the destination square and not a direction letter. The length of the list is the number of slides. If you step through the list on the start board, you should finish at 1 2 3 / 4 5 6 / 7 8 0.
8-puzzle A*: FAQ
How does A* solve the 8-puzzle?
A* searches 8-puzzle boards by always expanding the position with the smallest f = g + h, where g is the number of slides so far and h is a lower bound on the slides still needed. With Manhattan distance and weight 1, the first time the goal is chosen, the path behind it is a shortest solution.
What is Manhattan distance on the 8-puzzle?
It is the sum, over each numbered tile, of the row distance plus the column distance from that tile to its goal square. The blank is not included. A tile two rows and one column away contributes 3 to the sum.
Why can A* trust Manhattan distance on this puzzle?
A legal slide moves one tile by one square, so no tile can reach its goal in fewer slides than its Manhattan distance, and the sum over tiles does not over-count. That makes the heuristic admissible, which is the condition A* needs for a shortest path.
How do I know an 8-puzzle is solvable before I search?
Ignore the blank and count inversions among the eight tiles. For the usual goal, with the blank in the bottom-right corner, an even count is solvable and an odd count is not. Run this test first and skip A* when the count is odd.
How do I code an 8-puzzle solver in Python with A*?
The listing above is a complete 3×3 example: an inversion check, a Manhattan-distance function, and an A* loop that returns the tiles to slide. Start with a one-move board such as (1, 2, 3, 4, 5, 6, 7, 0, 8), which should print [8].
Does this site’s 3×3 solver return a shortest path?
Yes. The solver page states that on 3×3, no arrangement of moves reaches the goal in fewer steps. The 4×4 mode on the same page returns a working path and does not claim a shortest path.
Can I use this Python listing on a 15 puzzle?
The functions above are written for a 3×3 board and the 181,440-state reachable set. A 15-puzzle shortest-path solver needs a different design. This site’s 4×4 solver will still accept a numbered 15-puzzle and return a working path, without claiming that path is shortest.
What does the Python output list mean?
It is the sequence of tiles that slide into the blank. The length of the list is the number of moves. None means the start board failed the inversion test, so no path is searched for.