Snakes and Ladders - Problem

You are given an n x n integer matrix board where the cells are labeled from 1 to in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.

You start on square 1 of the board. In each move, starting from square curr, do the following:

  • Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n²)]. This choice simulates the result of a standard 6-sided die roll.
  • If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.
  • The game ends when you reach the square .

A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c].

Squares 1 and are not the starting points of any snake or ladder.

Note: You only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.

Return the least number of dice rolls required to reach the square . If it is not possible to reach the square, return -1.

Input & Output

Example 1 — Small Board with Ladder
$ Input: board = [[-1,4],[-1,3]]
Output: 1
💡 Note: Start at 1. Roll die to reach 2, but there's a ladder at position 2 that takes you directly to position 4 (the target). Total moves: 1.
Example 2 — Larger Board
$ Input: board = [[-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]]
Output: 4
💡 Note: 36 cells total. Need minimum 4 dice rolls to reach cell 36, using optimal path that may include ladders and avoiding snakes.
Example 3 — Impossible Case
$ Input: board = [[-1,-1],[-1,1]]
Output: -1
💡 Note: There's a snake at position 4 that brings you back to position 1, creating an infinite loop. Impossible to reach the target.

Constraints

  • n == board.length == board[i].length
  • 2 ≤ n ≤ 20
  • board[i][j] is either -1 or in the range [1, n²]
  • The squares labeled 1 and n² do not have any ladders or snakes

Visualization

Tap to expand
Snakes and Ladders: Find Minimum Dice Rolls12345678916Ladder→4BFS Exploration1Start27Roll 1-64Target!Ladder JumpSolution: Use BFS to find minimum path from 1 to n²Handle Boustrophedon numbering + snakes/ladders + 6-sided die constraints
Understanding the Visualization
1
Input
n×n board with snakes (-1) and ladders (destination)
2
Process
BFS from position 1, try dice rolls 1-6 each turn
3
Output
Minimum moves to reach position n²
Key Takeaway
🎯 Key Insight: BFS naturally finds shortest paths in unweighted graphs like this board game
Asked in
Amazon 15 Microsoft 12 Google 8
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen