Snakes and Ladders (LeetCode 909): Solution and Explanation

Medium
Array
Breadth First Search
Matrix

Squares on an n x n board are numbered in a zigzag from the bottom-left. Starting on square 1 and rolling a die each move, with snakes and ladders forcing a jump, find the fewest moves to reach square n², or -1 if it cannot be done.

Intuition

You control the die, so the question is not about luck. Each move you may choose any of the next six squares, which makes this a shortest-path question on a graph whose nodes are the squares.

Every move costs exactly one, whatever you roll. In a graph where all edges have the same weight, breadth-first search reaches each node first along a shortest route.

Snakes and ladders only change where an edge points. If rolling onto square 17 sends you down a snake to 13, the edge from the current square goes to 13 instead of 17. You never chain a second jump in the same move.

The only fiddly part is reading the board: row 0 of the matrix is the top, and every other row runs right to left. A small helper that turns a label into (row, col) keeps the BFS clean.

Approach: Breadth-first search over squares

  1. Write a mapping from label s to a cell: r = (s - 1) / n counts rows from the bottom, the matrix row is n - 1 - r, and the column is c on even r and n - 1 - c on odd r.
  2. Start BFS with square 1 at distance 0.
  3. Pop a square s. If it is n², return its distance.
  4. For each roll result next in s + 1 .. min(s + 6, n²), look up the cell. If it holds a value other than -1, replace next with that destination.
  5. If the destination has no distance yet, give it dist[s] + 1 and push it. If the queue empties first, return -1.

Step-by-step example

board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
  1. The board is 6 x 6, so the goal is square 36. Square 2 has a ladder to 15, square 14 a ladder to 35, and square 17 a snake to 13.
  2. Pop 1 (0 moves). Rolls land on 2..7. Square 2 climbs to 15, so the new squares at 1 move are 15, 3, 4, 5, 6 and 7.
  3. Pop 15 first: its rolls cover 16..21, and 17 slides down the snake to 13. So 16, 13, 18, 19, 20 and 21 get 2 moves. The squares 3..7 then add 8..12 at 2 moves.
  4. From 13 at 2 moves, rolling 1 lands on 14 and the ladder lifts it to 35, so 35 gets 3 moves.
  5. From 35, rolling 1 reaches 36 at 4 moves. When 36 is dequeued, BFS returns 4.

Code: Python, Java, C++

1class Solution:
2    def snakesAndLadders(self, board: List[List[int]]) -> int:
3        n = len(board)
4        target = n * n
5        dist = {1: 0}
6        queue = deque([1])
7        while queue:
8            s = queue.popleft()
9            if s == target:
10                return dist[s]
11            for nxt in range(s + 1, min(s + 6, target) + 1):
12                r, c = divmod(nxt - 1, n)
13                row, col = n - 1 - r, (c if r % 2 == 0 else n - 1 - c)
14                dest = nxt if board[row][col] == -1 else board[row][col]
15                if dest not in dist:
16                    dist[dest] = dist[s] + 1
17                    queue.append(dest)
18        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

There are n² squares. Each is dequeued at most once and tries at most six rolls, so the work is 6 * n² steps.

Space

O(n^2)

The distance table and the queue each hold at most one entry per square.

Other approaches

Dijkstra's algorithm (time O(n^2 log n), space O(n^2))

Works because all weights are non-negative, but every edge costs 1, so the priority queue only adds a log factor over plain BFS.

Flatten the board first (time O(n^2), space O(n^2))

Copy the board into a 1D array jump[1..n²] in label order before the BFS. The search then indexes the array directly. Same complexity, and the label-to-cell logic lives in one loop.

Common mistakes

  • Getting the zigzag wrong. The bottom row runs left to right, the next runs right to left, and the matrix row index is counted from the top.
  • Following a chain of jumps. If a ladder ends on the start of a snake, you stay at the ladder's end for that move.
  • Marking a square visited when you land on it instead of where you end up. The node you enqueue and mark is the jump destination.
  • Using DFS or greedy 'always take the biggest roll'. A smaller roll can hit a ladder, so only BFS guarantees the minimum.

Frequently asked questions

Why does BFS give the fewest moves?

Each move is one edge of weight one. BFS visits squares in order of distance from square 1, so the first time it reaches n² it has used the fewest possible moves.

Can a snake ever be part of the best route?

Yes. A snake can drop you onto a square that is one roll away from a long ladder. BFS treats snakes as ordinary edges, so it finds such routes automatically.

What if the destination of a ladder is the start of another ladder?

You do not climb the second one in the same move. The edge ends at the first ladder's top. The second ladder only matters if a later roll lands on its start square.

When is the answer -1?

When every square you can reach leads only to squares you have already seen, for example when six squares in a row all hold snakes back to the start. The queue empties before n² is reached.