#909

Snakes and Ladders

Medium
ArrayBreadth-First SearchMatrixBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal approach uses Breadth-First Search (BFS) to explore the board level by level. This ensures that we find the shortest path to the end square efficiently, as BFS explores all possible moves from the current square before moving deeper.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue for BFS starting from square 1.
  2. 2Step 2: For each square, explore all possible moves (1 to 6) and check if there is a snake or ladder.
  3. 3Step 3: If we reach square n², return the number of rolls taken. If the queue is exhausted, return -1.
solution.py21 lines
1from collections import deque
2
3def snakesAndLadders(board):
4    n = len(board)
5    queue = deque([(1, 0)])  # (current square, rolls)
6    visited = set([1])
7    while queue:
8        curr, rolls = queue.popleft()
9        if curr == n * n:
10            return rolls
11        for move in range(1, 7):
12            next_square = curr + move
13            if next_square > n * n:
14                continue
15            r, c = divmod(next_square - 1, n)
16            if board[n - 1 - r][c] != -1:
17                next_square = board[n - 1 - r][c]
18            if next_square not in visited:
19                visited.add(next_square)
20                queue.append((next_square, rolls + 1))
21    return -1

Complexity note: The time complexity is O(n²) because we may need to visit each square on the board, and the space complexity is O(n) due to the queue used for BFS.

  • 1Using BFS ensures we find the shortest path efficiently.
  • 2Understanding the board layout is crucial for correct indexing.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.