Skip to content

Snakes and Ladders

You are given an n x n integer matrix board where the cells are labeled from 1 to in a Boustrophedon style (left-to-right in even rows, right-to-left in odd rows).

Some cells contain snakes or ladders:

  • board[r][c] > 0: Ladder takes you from that cell to board[r][c]
  • board[r][c] == -1: Regular cell (no snake or ladder)
  • Snakes and ladders are represented differently in the problem (negative values or special encoding)

You start at square 1 on the board. On each turn:

  • Roll a dice (you can move 1 to 6 steps forward)
  • If you land on a square with a ladder, you climb it
  • If you land on a square with a snake, you slide down
  • Return the minimum number of dice rolls needed to reach square
nboard setupOutputExplanation
2[[-1,-1],[-1,-1]]1Roll 1: 1 → 2. No snakes/ladders. Already at n²=4 is impossible in 1 move; actual minimum is 2.
2[[-1,-1],[-1,3]]1From position 1, roll 1 to reach position 2, then roll 2 to reach position 4. Minimum is 2.
3[[-1,2,-1],[4,3,-1],[2,-1,-1]]2Use ladders strategically to reach position 9 in minimum rolls.
4[[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,-1],[-1,-1,-1,5]]3Simple board progression without snakes/ladders: reach position 16 in 3 rolls (1→6→12→16).
  • 2 <= n <= 100
  • board.length == board[i].length == n
  • 1 <= board[i][j] <= n² or board[i][j] == -1
  • The cells labeled 1 and have board[i][j] == -1
  • There is at most one snake or ladder per cell
  • board[i][j] != board[j][i] (snakes and ladders are unique per cell)
ApproachTimeSpaceNotes
BFSO(n)O(n)First approach
DFSO(n)O(n)Second approach
★ Recommended
⏱ Time O(n) 💾 Space O(n)
snakes_and_ladders_bfs.py
from collections import deque
def snakesAndLadders(board):
"""BFS to find shortest path in game board."""
n = len(board)
def get_coords(pos):
pos -= 1
row = n - 1 - pos // n
col = pos % n if (n - 1 - row) % 2 == 0 else n - 1 - pos % n
return row, col
queue = deque([(1, 0)])
visited = {1}
while queue:
pos, moves = queue.popleft()
if pos == n * n:
return moves
for i in range(1, 7):
next_pos = pos + i
if next_pos > n * n:
break
row, col = get_coords(next_pos)
if board[row][col] != -1:
next_pos = board[row][col]
if next_pos not in visited:
visited.add(next_pos)
queue.append((next_pos, moves + 1))
return -1
✓ Simple
⏱ Time O(n) 💾 Space O(n)
snakes_and_ladders_dfs.py
def snakesAndLadders(board):
"""DFS with memoization to find shortest path."""
n = len(board)
def get_coords(pos):
pos -= 1
row = n - 1 - pos // n
col = pos % n if (n - 1 - row) % 2 == 0 else n - 1 - pos % n
return row, col
memo = {}
def dfs(pos):
if pos == n * n:
return 0
if pos in memo:
return memo[pos]
result = float('inf')
for i in range(1, 7):
next_pos = pos + i
if next_pos > n * n:
break
row, col = get_coords(next_pos)
if board[row][col] != -1:
next_pos = board[row][col]
result = min(result, 1 + dfs(next_pos))
memo[pos] = result
return result
ans = dfs(1)
return ans if ans != float('inf') else -1