Snakes and Ladders solution explained
Snakes and Ladders asks for the fewest die rolls from square 1 to the last square of an n by n board, where squares are numbered in a zigzag from the bottom-left and some squares send you to another square. Treat each square as a node with up to six outgoing moves (rolls 1 to 6), replace a landing square by its snake or ladder destination, and run a BFS from square 1. The first time the BFS reaches square n², its level is the answer, in O(n²) time. Converting square numbers to grid cells correctly is the hard part.
By Evin JohnPublished 7 min read
The rules, restated
You get an n by n board. Squares are labelled 1 to n², starting at the bottom-left cell, running left to right along the bottom row, then right to left along the row above, and so on, switching direction every row. Each cell holds -1 or the number of a square. You start on square 1. In one move, pick a value from 1 to 6 (you choose it, it is not random) and advance that many squares, without passing n². If the square you land on holds a number other than -1, you move to that square: a ladder if it is higher, a snake if it is lower. You follow it once, even if the destination also has one. Return the fewest moves to reach square n², or -1.
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 (top) | 7 | 8 | 9 |
| 1 | 6 | 5 | 4 |
| 2 (bottom) | 1 | 2 | 3 |
| Board | Answer | Why |
|---|---|---|
| 3 by 3, no snakes or ladders | 2 | Roll 6 to square 7, then 2 to square 9. |
| 4 by 4, no snakes or ladders | 3 | 1 to 7 to 13 to 16; two rolls cover at most 12 squares. |
| 4 by 4, ladder on square 6 going to 15 | 2 | Roll 5 onto the ladder, climb to 15, roll 1. |
| A board where squares 2 to 7 all hold snakes back to 1 | -1 | Every roll from square 1 sends you back to it. |
Why it gets asked
Interviewers use it to test two things at once. The first is recognising a shortest-path question on an implicit graph: squares are states, rolls are moves of equal cost, so BFS. The second is careful index handling: the zigzag numbering, rows counted from the top in the array but squares counted from the bottom, and the one-jump rule. Most wrong answers come from the second part, not the first.
Mapping a square to a cell
Subtract 1 from the square number to make it 0-based, then divide by n. The quotient is the row counted from the bottom, and the remainder is the position within that row. The array row is n - 1 minus the row from the bottom. On rows with an even index from the bottom, the position is the column; on odd ones, the row runs right to left, so the column is n - 1 minus the position. For square 6 on a 4 by 4 board: 5 divided by 4 is 1 remainder 1, so array row 2, and since that row runs right to left, column 2.
BFS over squares
from collections import deque
def square_to_cell(square, n):
row_from_bottom, offset = divmod(square - 1, n)
row = n - 1 - row_from_bottom
col = offset if row_from_bottom % 2 == 0 else n - 1 - offset # rows alternate direction
return row, col
def snakes_and_ladders(board):
n = len(board)
last = n * n
moves = {1: 0}
queue = deque([1])
while queue:
square = queue.popleft()
if square == last:
return moves[square]
for roll in range(1, 7):
nxt = square + roll
if nxt > last:
break
r, c = square_to_cell(nxt, n)
if board[r][c] != -1:
nxt = board[r][c] # take the snake or ladder, once
if nxt not in moves:
moves[nxt] = moves[square] + 1
queue.append(nxt)
return -1The visited check happens after the snake or ladder is applied, on the square where you actually end up. Two different rolls can land on different squares that both lead to the same destination; only the first one should be recorded. Square n² is reached either by an exact roll or by a ladder that ends there, and both are handled because the check is on the final square.
function snakesAndLadders(board) {
const n = board.length;
const last = n * n;
// jump[s] = where you end up after landing on square s
const jump = new Array(last + 1);
let square = 1;
for (let k = 0; k < n; k++) {
const row = n - 1 - k;
const cols = [...Array(n).keys()];
if (k % 2 === 1) cols.reverse();
for (const col of cols) {
jump[square] = board[row][col] === -1 ? square : board[row][col];
square++;
}
}
const moves = new Array(last + 1).fill(-1);
moves[1] = 0;
const queue = [1];
for (let head = 0; head < queue.length; head++) {
const s = queue[head];
if (s === last) return moves[s];
for (let roll = 1; roll <= 6 && s + roll <= last; roll++) {
const t = jump[s + roll];
if (moves[t] === -1) {
moves[t] = moves[s] + 1;
queue.push(t);
}
}
}
return -1;
}Building the jump array walks the rows from the bottom up and reverses every other one, which mirrors the numbering directly. After that the BFS never touches the 2D board, and the bug surface shrinks to one loop. In an interview, this split is easy to explain and easy to test: print jump for a 3 by 3 board and check it against the numbering table.
Why not a greedy roll
Always rolling 6 feels right, but it can skip a ladder that a shorter roll would hit, or land on a snake that a different roll would avoid. In the 4 by 4 example with a ladder on square 6, rolling 6 from square 1 lands on 7 and misses it, and the game takes 3 moves instead of 2. BFS tries all six rolls at every level, so it cannot miss a better route.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Repeated relaxation (Bellman-Ford style) | O(N²) in the worst case | O(N) |
| BFS over squares | O(N), six edges per square | O(N) |
Edge cases
- A 2 by 2 board: square 4 is one roll away.
- A ladder whose destination has its own ladder or snake: you stop at the destination.
- A snake back to square 1: square 1 is already visited, so it is ignored.
- Six snakes in a row that trap every roll from some square: -1 if no other route exists.
- A ladder ending exactly on n².
Mistakes
- Numbering every row left to right, forgetting the zigzag.
- Treating array row 0 as the bottom row.
- Following a chain of snakes and ladders in one move.
- Marking the square you landed on as visited instead of the square after the jump.
- Allowing a roll past n² instead of stopping at it.
- Rolling 6 greedily.
How to explain it out loud
Fictional example
- Candidate
- Each square is a state, and from each one I can roll one to six, so up to six moves of equal cost. Fewest rolls is a BFS distance.
- Candidate
- The tricky part is the numbering, so I'll first flatten the board into an array where entry s is where you end up after landing on square s, walking rows from the bottom and reversing every other row.
- Interviewer
- What if a ladder leads onto another ladder?
- Candidate
- Only one jump per move, so the flattened array maps each square to one destination and I never follow a second. Then the BFS is linear in the number of squares.
Related problems
The same state-space BFS solves Open the Lock, and Shortest Path in Binary Matrix applies it to a grid with eight moves. Word Break II and Longest Increasing Path in a Matrix move on to memoized search, and for index arithmetic practice on grids, Number of Islands is a gentler start.
Studying it with Natively
Index mapping is where this problem goes wrong, so a second pair of eyes helps. Natively can read the board problem from a screenshot on Mac or Windows and show an approach and code in its overlay, which you can test against your own square-to-cell function. Explaining it aloud in a mock, you get a transcript afterwards to see whether you mentioned the one-jump rule. See the AI interview assistant.
Questions people ask
How do you solve Snakes and Ladders?
Treat each square as a node with six moves, one per roll. Replace the landing square with its snake or ladder destination, then BFS from square 1 until square n² is reached.
How do you convert a square number to a board cell?
Subtract 1 and divide by n: the quotient is the row from the bottom, the remainder the position in the row. Flip the row index for the array, and reverse the column on every other row.
Do you follow two ladders in one move?
No. After landing, you take at most one snake or ladder, even if its destination has another one.
Why not always roll a 6?
A shorter roll can land on a ladder or avoid a snake. BFS tries all six rolls at every step, so it always finds the fewest moves.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
