Skip to content
Problem 773 · LeetCode 773(opens in a new tab)

Sliding Puzzle

HardBreadth-first search

A 2 × 3 tray holds tiles numbered 1 to 5 and one empty square, written as 0. In one move you slide a tile that is next to the empty square (up, down, left or right) into it. In other words, 0 swaps places with one of its neighbours.

The puzzle is solved when the tray reads [[1,2,3],[4,5,0]]. Return the fewest moves that solve board, or −1 if no sequence of moves ever solves it.

Example 1

Input:  board = [[1,0,2],[4,5,3]]
Output: 2
Why:    slide 2 left, then 3 up
2 more examples and the constraints

Example 2

Input:  board = [[2,1,3],[4,5,0]]
Output: -1
Why:    swapping just 1 and 2 is never reachable

Example 3

Input:  board = [[1,2,3],[4,5,0]]
Output: 0
Why:    already solved

Constraints

  • board is 2 × 3
  • board holds each of 0, 1, 2, 3, 4, 5 exactly once

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DFS with best-depth memoO(S²)
  2. Breadth-first searchO(S)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for the hardest boardVerdict
DFS with best-depth memoO(S²)
Correct; searches boards again
Breadth-first searchO(S)
Best; each board once

S = number of boards, at most 6! = 720 (only 360 reachable from any start).

Edge cases to test

  • Already solved. Return 0 before making any move.
  • Unsolvable board. Half of all boards can never be solved; BFS empties its queue and returns −1.
  • Hardest boards. Some boards need 21 moves, e.g. [[4, 5, 0], [1, 2, 3]]. BFS handles them like any other.
  • Empty square in a corner. Only two moves are possible from a corner.

Common mistakes

  • Marking a board seen when it is popped instead of when it is queued, so the same board enters the queue many times.
  • Incrementing moves after every pop instead of after every round.
  • Building neighbours with row and column math and swapping across the row boundary (index 2 with 3).

How to talk through it

  1. 1Clarify. Is the board always 2 × 3 with one 0? What if it cannot be solved?
  2. 2Model as a graph. Boards are nodes, slides are edges, every edge costs 1.
  3. 3Pick BFS. Shortest path in an unweighted graph; DFS would revisit boards.
  4. 4Code it. String boards, a fixed neighbour table, a queue and a seen set, rounds for the move count.
  5. 5Test out loud. Run the solved board (0) and a single swapped pair (−1).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?