SDE & MLE Prep

909. Snakes and Ladders

Problem

The squares of an n×n board are numbered 1…n² starting at the bottom-left, snaking left-to-right then right-to-left row by row going up. board[r][c] is −1 or the destination of a snake/ladder starting there. From square s, a die roll moves you to any of s + 1 … s + 6; if that square has a snake or ladder you must take it (but not a second one in the same move). Return the fewest moves from 1 to n², or −1.

Example: the 6×6 board with ladders 2 → 15 and 14 → 35 and snake 17 → 13 → 4

Constraints: n ≤ 20.

BFS over squares 1..n². The only tricky part is mapping square s to (row, col) on a boustrophedon board: r = (s−1) // n, c = (s−1) % n, reversed on odd rows, and rows counted from the bottom.

Complexity: O(n²).

class Solution:
    def snakesAndLadders(self, board: List[List[int]]) -> int:
        n = len(board)

        def cell(s):
            r, c = divmod(s - 1, n)
            if r % 2:
                c = n - 1 - c
            return board[n - 1 - r][c]

        q, seen, moves = deque([1]), {1}, 0
        while q:
            for _ in range(len(q)):
                s = q.popleft()
                if s == n * n:
                    return moves
                for nxt in range(s + 1, min(s + 6, n * n) + 1):
                    dest = cell(nxt) if cell(nxt) != -1 else nxt
                    if dest not in seen:
                        seen.add(dest)
                        q.append(dest)
            moves += 1
        return -1