LeetCode 909: Snakes and Ladders — Python Solution

Solve LeetCode 909: Snakes and Ladders in Python with a board-index BFS approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicGraph BFS
Reusable patternboard-index BFS
ComplexityO(n^2) time and O(n^2) space

What the problem is testing

Map square numbers to boustrophedon coordinates and BFS over dice results, applying at most one snake or ladder per move.

Algorithm

  1. Map square numbers to boustrophedon coordinates and BFS over dice results, applying at most one snake or ladder per move.
  2. Maintain this invariant: The first time BFS reaches a square uses the minimum number of dice throws.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def snakesAndLadders(self, board):
        n = len(board)
        def coordinates(square):
            row_from_bottom, offset = divmod(square - 1, n)
            row = n - 1 - row_from_bottom
            col = offset if row_from_bottom % 2 == 0 else n - 1 - offset
            return row, col
        queue, seen = deque([(1, 0)]), {1}
        while queue:
            square, moves = queue.popleft()
            if square == n * n: return moves
            for rolled in range(square + 1, min(square + 6, n * n) + 1):
                r, c = coordinates(rolled)
                destination = board[r][c] if board[r][c] != -1 else rolled
                if destination not in seen:
                    seen.add(destination); queue.append((destination, moves + 1))
        return -1

Why this is correct

The proof follows the maintained state: The first time BFS reaches a square uses the minimum number of dice throws. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n^2) time and O(n^2) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Do not chain a second jump in the same move; row direction alternates from the bottom.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 210. Course Schedule II · Next: 433. Minimum Genetic Mutation