InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Snakes and Ladders

medium Original ↗ 00:00

Problem

You’re given an n x n board. The cells are numbered 1 to in a boustrophedon (“ox-plowing”) layout: numbering starts at the bottom-left corner, runs left-to-right along the bottom row, then the direction flips on each row moving upward.

You start on cell 1. On each move you roll a die and advance to any cell in [current + 1, current + 6] that exists on the board. If that landing cell holds a snake or ladder, you immediately move to its destination — but you take at most one snake/ladder per move (you do not chain into a second one from the destination).

board[r][c] is -1 for an ordinary cell, or the destination cell number of a snake/ladder. Return the least number of moves to reach cell , or -1 if it’s unreachable.

Examples

  • board = [[-1,-1],[-1,3]]1 — cell 2 is a ladder to 3, but from cell 1 you can also roll a 3 straight to cell 4 () in one move.
  • 6×6 board with board[5][1]=15 (cell 2→15), board[3][1]=35 (cell 14→35), board[3][4]=13 (cell 17→13) → 41 →2(↑15) →17(↓13) →14(↑35) →36.
  • board = [[-1,-1,-1],[-1,9,8],[-1,8,9]]1 — from cell 1, reaching cell 2 or beyond and taking a ladder lands you on 9 () in one move.

Constraints

  • 2 <= n <= 20, so at most 400 cells.
  • Every move has the same cost (one roll), which is the key to the expected complexity.
  • A cell that is itself a snake/ladder head is never a valid resting square — you only stop on its destination.

Think about it first

Hint 1 Model each cell as a graph node. From cell x there is an edge to each of x+1 … x+6 (following any snake/ladder at the landing cell). Every edge costs one move — so this is a shortest-path problem on an unweighted graph.
Hint 2 Shortest path with uniform edge cost is exactly what breadth-first search computes: the first time BFS reaches a node, it does so in the fewest moves. DFS would explore paths but can't guarantee the minimum without exhaustively trying everything.
Hint 3 The only fiddly part is converting a 1-based cell number to a (row, col) on the boustrophedon board. Use divmod(cell - 1, n): the quotient tells you how many rows up from the bottom, and its parity tells you whether that row runs left-to-right or right-to-left.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug