Snakes and Ladders

Pattern: Shortest paths

medium

Squares are vertices; a die roll moves 1 to 6 squares, then a snake or ladder (if any) jumps you to its end. Every roll costs one move, so BFS from square 1 gives the fewest rolls to reach the last square. The board numbers squares in a zig-zag from the bottom-left.

The problem

Given an n × n board (squares numbered 1 to n² in a zig-zag starting at the bottom-left), where board[r][c] is -1 or the destination of a snake or ladder at that square, return the fewest die rolls to reach square n², or -1. A snake or ladder is followed only once per move.

Think first

  • What are the vertices and edges?
  • How do you convert a square number to a cell?
  • Can you follow two ladders in one move?

Hints

    Brute force, and why it fails

    Try every sequence of rolls: exponential.

    The key insight

    Every move costs one roll, so BFS over squares finds the minimum.

    Dry run

    rolls1

    The 6 × 6 LeetCode board. From square 1, roll to 2, which has a ladder to 15.

    Step 1 of 3

    The plan

    dest[s] = jump target or s (zig-zag)
    BFS from 1: for t in s + 1 .. s + 6: v = dest[t]; if unvisited: dist + 1
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Each square once with six moves.

    Edge cases

    • A 2 × 2 board.
    • A snake right before the end.
    • No snakes or ladders: ceil((n² - 1) / 6).
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int snakesAndLadders(int[][] board) {
            int n = board.length, goal = n * n;
            int[] dest = new int[goal + 1];         // dest[s]: where landing on square s really takes you
            int s = 1;
            for (int i = 0; i < n; i++) {           // squares run left to right, then right to left, from the bottom row up
                int r = n - 1 - i;
                for (int k = 0; k < n; k++) {
                    int c = i % 2 == 0 ? k : n - 1 - k;
                    dest[s] = board[r][c] == -1 ? s : board[r][c];
                    s++;
                }
            }
            int[] dist = new int[goal + 1];
            Arrays.fill(dist, -1);
            dist[1] = 0;
            Queue<Integer> q = new ArrayDeque<>();
            q.add(1);
            while (!q.isEmpty()) {                  // each throw is one step: BFS over squares
                int u = q.poll();
                if (u == goal) return dist[u];
                for (int t = u + 1; t <= Math.min(u + 6, goal); t++) {
                    int v = dest[t];
                    if (dist[v] == -1) { dist[v] = dist[u] + 1; q.add(v); }
                }
            }
            return -1;
        }
    }

    C++

    class Solution {
    public:
        int snakesAndLadders(vector<vector<int>>& board) {
            int n = static_cast<int>(board.size()), goal = n * n;
            vector<int> dest(goal + 1);             // dest[s]: where landing on square s really takes you
            int s = 1;
            for (int i = 0; i < n; i++) {           // squares run left to right, then right to left, from the bottom row up
                int r = n - 1 - i;
                for (int k = 0; k < n; k++) {
                    int c = i % 2 == 0 ? k : n - 1 - k;
                    dest[s] = board[r][c] == -1 ? s : board[r][c];
                    s++;
                }
            }
            vector<int> dist(goal + 1, -1);
            dist[1] = 0;
            queue<int> q;
            q.push(1);
            while (!q.empty()) {                    // each throw is one step: BFS over squares
                int u = q.front();
                q.pop();
                if (u == goal) return dist[u];
                for (int t = u + 1; t <= min(u + 6, goal); t++) {
                    int v = dest[t];
                    if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); }
                }
            }
            return -1;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def snakesAndLadders(self, board: list[list[int]]) -> int:
            n = len(board)
            goal = n * n
            dest = [0]                              # dest[s]: where landing on square s really takes you
            for i in range(n):                      # left to right, then right to left, from the bottom row up
                row = board[n - 1 - i]
                for c in (range(n) if i % 2 == 0 else range(n - 1, -1, -1)):
                    dest.append(len(dest) if row[c] == -1 else row[c])
            dist = {1: 0}
            q = deque([1])
            while q:                                # each throw is one step: BFS over squares
                u = q.popleft()
                if u == goal:
                    return dist[u]
                for t in range(u + 1, min(u + 6, goal) + 1):
                    v = dest[t]
                    if v not in dist:
                        dist[v] = dist[u] + 1
                        q.append(v)
            return -1

    Common mistakes

    • Getting the zig-zag numbering wrong.
    • Following chains of jumps.

    Similar problems