Sliding Puzzle (LeetCode 773): Solution and Explanation

Hard
Array
Breadth First Search
Memoization
Matrix
Dynamic Programming

A 2 x 3 board holds tiles 1 to 5 and a blank. Each move slides a neighbouring tile into the blank. Return the fewest moves to reach [[1,2,3],[4,5,0]], or -1 if that board cannot be reached. [[1,2,3],[4,0,5]] needs 1 move.

Intuition

The board is tiny: there are only 6! = 720 ways to place six symbols. That is small enough to treat every arrangement as a node in a graph.

One move connects two arrangements, and every move costs the same. The fewest moves is therefore the shortest path in an unweighted graph, which is exactly what breadth-first search finds.

Write each board as a 6-character string like "123405". The blank at index z can only swap with a fixed set of indices, so the neighbours of a board come from a small lookup table.

Approach: BFS over board states

  1. Flatten the board row by row into a string start. The goal is "123450".
  2. Precompute the swap targets for each blank position: [[1,3],[0,2,4],[1,5],[0,4],[1,3,5],[2,4]].
  3. Run BFS from start one level at a time, keeping a seen set. When a popped board equals the goal, return the current level steps.
  4. For each popped board, swap the blank with each target, and queue any board not yet seen.
  5. If the queue empties first, return -1.

Step-by-step example

board = [[1,2,3],[4,0,5]]
  1. start = "123405". Level 0 holds only this board, and it is not the goal.
  2. The blank is at index 4, which can swap with indices 1, 3 and 5. That makes "103425", "123045" and "123450", all new.
  3. Level 1 starts. The first board popped is "103425", not the goal, so its neighbours are queued.
  4. Soon "123450" is popped on level 1, so the answer is 1.

Code: Python, Java, C++

1class Solution:
2    def slidingPuzzle(self, board: List[List[int]]) -> int:
3        start = ''.join(str(c) for row in board for c in row)
4        target = '123450'
5        moves = [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]]
6        queue = deque([start])
7        seen = {start}
8        steps = 0
9        while queue:
10            for _ in range(len(queue)):
11                state = queue.popleft()
12                if state == target:
13                    return steps
14                z = state.index('0')
15                for nz in moves[z]:
16                    chars = list(state)
17                    chars[z], chars[nz] = chars[nz], chars[z]
18                    nxt = ''.join(chars)
19                    if nxt not in seen:
20                        seen.add(nxt)
21                        queue.append(nxt)
22            steps += 1
23        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O((mn)! * mn)

At most 720 boards are visited, and each one makes up to 3 neighbours with an O(6) string copy.

Space

O((mn)!)

The seen set and queue hold at most 360 reachable boards.

Other approaches

A* search (time O((mn)! log((mn)!)), space O((mn)!))

Order the frontier by moves so far plus the Manhattan distance of each tile to its home. It visits fewer boards on bigger puzzles but adds a heap and gains nothing at this size.

Bidirectional BFS (time O((mn)!), space O((mn)!))

Grow one frontier from the start and one from the goal and stop when they meet. Useful for larger boards like the 15-puzzle.

Parity check first (time O(1) check, space O(1))

Count inversions among the five tiles. On a 2 x 3 board, boards with the wrong parity can never be solved, so you can return -1 immediately before searching.

Common mistakes

  • Marking a board as seen only when it is popped instead of when it is queued. The same board then enters the queue many times.
  • Using DFS. It finds a path but not necessarily the shortest one.
  • Getting the neighbour table wrong. Index 2 (top right) can swap with 1 and 5, not with 3, because 3 is on the next row's left edge.

Frequently asked questions

Why can some boards never be solved?

Every move preserves a parity invariant of the tile order. Exactly half of the 720 arrangements share the goal's parity, so the other 360 are unreachable and BFS empties its queue after 360 boards.

What is the most moves ever needed?

21. For example [[4,5,0],[1,2,3]] needs 21 moves, the deepest level of the BFS from the goal.

Does this scale to bigger boards?

A 3 x 3 board has 9!/2 = 181,440 reachable states, still fine for BFS. The 4 x 4 fifteen puzzle has about 10^13, which needs A* or IDA* with a good heuristic.