909. Snakes and Ladders
Asked at 10Amazon41Google28Microsoft23Bloomberg22Meta18Tesla62Zomato62Anduril41TikTok26Goldman Sachs21
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
B = [[-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]]
assert Solution().snakesAndLadders(B) == 4
assert Solution().snakesAndLadders([[-1, -1], [-1, 3]]) == 1
class Solution {
public int snakesAndLadders(int[][] board) {
int n = board.length;
boolean[] seen = new boolean[n * n + 1];
Deque<Integer> q = new ArrayDeque<>(List.of(1));
seen[1] = true;
for (int moves = 0; !q.isEmpty(); moves++)
for (int k = q.size(); k > 0; k--) {
int s = q.poll();
if (s == n * n) return moves;
for (int nxt = s + 1; nxt <= Math.min(s + 6, n * n); nxt++) {
int r = (nxt - 1) / n, c = (nxt - 1) % n;
if (r % 2 == 1) c = n - 1 - c;
int v = board[n - 1 - r][c], dest = v == -1 ? nxt : v;
if (!seen[dest]) { seen[dest] = true; q.add(dest); }
}
}
return -1;
}
}
func snakesAndLadders(board [][]int) int {
n := len(board)
cell := func(s int) int { // board value of square s (boustrophedon from the bottom-left)
r, c := (s-1)/n, (s-1)%n
if r%2 == 1 {
c = n - 1 - c
}
return board[n-1-r][c]
}
q, seen := []int{1}, map[int]bool{1: true}
for moves := 0; len(q) > 0; moves++ {
next := []int{}
for _, s := range q {
if s == n*n {
return moves
}
for nxt := s + 1; nxt <= min(s+6, n*n); nxt++ {
dest := nxt
if v := cell(nxt); v != -1 {
dest = v
}
if !seen[dest] {
seen[dest] = true
next = append(next, dest)
}
}
}
q = next
}
return -1
}