Snakes and Ladders
Problem Statement
You are given an n × n board. Its squares are numbered from 1 to n² in a snake-like order: the bottom row goes left to right, the row above it goes right to left, and so on. You start on square 1.
Each roll moves you to any one of the next 6 squares: from square s you can land on s + 1, …, s + 6, but never past square n².
If the square you land on has a snake or a ladder, you must take it to its destination. You take at most one snake or ladder per roll. If that destination is the start of another snake or ladder, you stay where you are and do not follow it.
Return the fewest rolls needed to reach square n². If it cannot be reached, return -1.
board, an n × n grid. Row 0 is the top row of the grid. board[r][c] is -1 if that square has no snake or ladder. Otherwise it is the square the snake or ladder sends you to.
The fewest number of rolls to reach square n², or -1.
Roll 1 goes from 1 to 2 and climbs the ladder to 15. Roll 2 goes from 15 to 17 and slides down the snake to 13. Roll 3 goes from 13 to 14 and climbs the ladder to 35. Roll 4 goes from 35 to 36, the last square.
On a 2 × 2 board, a roll of 3 from square 1 lands on square 4, the last square.
Roll 1 goes from 1 to 2, which is a ladder to 9. You stop on 9, and its ladder to 14 is not taken in the same roll. Roll 2 goes from 9 to 15. Roll 3 goes from 15 to 16. Three rolls.
- • The board is n × n, with 2 ≤ n ≤ 20.
- • Each cell holds -1 or a square number from 1 to n².
- • Squares 1 and n² never have a snake or ladder.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Repeat full passes over the squares, shortening roll counts, until a whole pass changes nothing
BFS from square 1: each roll is one edge, and at most one snake or ladder is taken per roll
Give square 1 a roll count of 0 and every other square ∞. In each pass, look at every square and update the squares its rolls reach if that gives a smaller count. Keep making passes until a whole pass changes nothing. Then every count is final.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.