Skip to problem
←

Snakes and Ladders

Medium 0 attempts

Given an n × n board, return the minimum number of die rolls needed to travel from square 1 to square n².

Squares are numbered from the bottom-left, left to right across the bottom row, then right to left across the next row, alternating upward. The input array is still stored in the usual top-row-first order.

For each turn:

  1. Choose a destination from current + 1 through min(current + 6, n²). Moves cannot overshoot the final square.
  2. If that square contains -1, stay there. Otherwise, you must move to the destination label stored in that cell.
  3. Follow at most one snake or ladder in this turn. If its destination has another jump, do not follow that second jump.

The jump does not cost an additional roll. Return -1 if the final square cannot be reached. You are finding the fewest possible rolls, not an expected value over random dice outcomes.

Function contract

Implement snakesAndLadders(board).

Output: Return the minimum number of die rolls needed to reach square n^2, or -1 if it is unreachable.

Example 1

Input
board = [[-1,-1],[-1,-1]]
Output
1

Example 2

Input
board = [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
Output
2
Visual Aid
Square labels on a 3 × 3 board
789654123Start at 1 · Finish at 9

These are square labels, not cell values. The top array row contains squares 7, 8, and 9; a cell value gives a jump destination or -1.

Constraints
  • n == board.length == board[i].length
  • 2 <= n <= 20
  • Each board[i][j] is -1 or a destination label from 1 to n^2
  • Squares 1 and n^2 contain no snake or ladder

Breadth-First Search

Treat each square as a state. Each edge represents one legal die roll followed by its mandatory jump, if any. BFS visits states in increasing roll count, so the first arrival at the final square is optimal. Mark the post-jump destination visited to handle cycles without reprocessing states.

Convert a label to its row counted from the bottom, reverse the column on odd-numbered rows, then convert to the top-first array row.

javascript
function snakesAndLadders(board) {
  const n = board.length;
  function getRC(s) {
    const r = Math.floor((s-1)/n), c = (s-1)%n;
    return [n-1-r, r%2===0 ? c : n-1-c];
  }
  const visited = new Set([1]), q = [[1, 0]];
  let head = 0;
  while (head < q.length) {
    const [pos, moves] = q[head++];
    for (let i = 1; i <= 6; i++) {
      let next = pos + i; if (next > n*n) continue;
      const [r, c] = getRC(next);
      if (board[r][c] !== -1) next = board[r][c];
      if (next === n*n) return moves + 1;
      if (!visited.has(next)) { visited.add(next); q.push([next, moves+1]); }
    }
  }
  return -1;
}

Time: O(n²) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript