Snakes and Ladders - Problem
Welcome to the classic Snakes and Ladders board game! π²
You're given an n Γ n board where squares are numbered from 1 to nΒ² in a special zigzag pattern called Boustrophedon. Starting from the bottom-left corner (square 1), numbers alternate direction on each row - like how an ox plows a field back and forth!
Game Rules:
- π― Goal: Reach square nΒ² with minimum dice rolls
- π² Movement: Each turn, roll a 6-sided die (move 1-6 squares)
- π Snakes: If you land on a snake's head, slide down to its tail
- πͺ Ladders: If you land on a ladder's bottom, climb up to its top
- β οΈ Important: Only take ONE snake/ladder per dice roll, even if the destination has another!
The board matrix uses -1 for normal squares and positive numbers for snake/ladder destinations. Return the minimum number of dice rolls needed to win, or -1 if impossible.
Input & Output
example_1.py β Basic 6x6 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:
Optimal path: 1β2β15β26β27β28β29β30β31β32β33β34β35β36 using moves: 1β2 (roll 1), 2β15 (ladder), 15β26 (roll 6+5=11, but max 6 so multiple rolls), reach 36 in 4 total moves
example_2.py β Small 3x3 Board
$
Input:
board = [[-1,-1],[-1,3]]
βΊ
Output:
1
π‘ Note:
Start at 1, roll any number β₯2 to reach squares 3 or 4. Square 3 has ladder to square 3 (no change), square 4 is the target. Only 1 move needed.
example_3.py β Impossible Case
$
Input:
board = [[-1,-1,-1],[-1,-1,-1],[-1,2,-1]]
βΊ
Output:
-1
π‘ Note:
Target is square 9. From square 8, there's a snake back to square 2, making it impossible to reach square 9.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Board
Convert the 2D matrix to a 1D game board with boustrophedon numbering
2
BFS Exploration
Use a queue to explore all positions reachable in 1 move, then 2 moves, etc.
3
Handle Special Squares
When landing on snakes or ladders, immediately move to their destinations
4
Track Visited
Mark visited squares to avoid infinite loops and redundant work
5
Find Shortest Path
Return the number of moves when target is first reached
Key Takeaway
π― Key Insight: BFS is perfect for finding the shortest path in unweighted graphs. Each dice roll has equal 'cost', making BFS the optimal choice for this minimum moves problem.
Time & Space Complexity
Time Complexity
O(nΒ²)
Each square is visited at most once, and we have nΒ² squares total
β Quadratic Growth
Space Complexity
O(nΒ²)
Queue and visited set can store up to nΒ² positions
β Quadratic Space
Constraints
- n == board.length == board[i].length
- 2 β€ n β€ 20
- -1 β€ board[i][j] β€ n2
- Squares 1 and n2 do not have snakes or ladders
- Only take one snake/ladder per dice roll
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code