26 · Graphs: BFS & DFS

#909 Snakes and Ladders

Mediumsolve on LeetCode ↗

frequently reported atAmazonGoogleMicrosoftBloombergMeta

the problem

In plain words

An n × n board numbers its squares 1 to n², starting at the bottom-left and zig-zagging upwards: left → right on the bottom row, right → left on the next, and so on. You start on square 1. Each roll moves you 1 to 6 squares forward (never past n²). If you land on a square whose board[r][c] isn't -1, you must jump to square board[r][c] — a snake or a ladder — but only once per roll, even if that square starts another jump. Return the fewest rolls to reach square n², or -1 if it can't be done.

in 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]]

out 4

Roll to 2 → ladder to 15. Roll to 17 → snake to 13. Roll to 14 → ladder to 35. Roll to 36.

in board = [[-1,-1],[-1,3]]

out 1

Roll a 3 and land on square 4, the last square. (Square 2 has a ladder to 3, but that doesn't help.)

  • n == board.length == board[i].length
  • 2 ≤ n ≤ 20
  • board[i][j] is -1 or in [1, n²]
  • Squares 1 and n² have no snake or ladder

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #127
      Word Ladder
      Hardin Graphs
    2. #1197
      Minimum Knight Moves
      Mediumin GraphsLeetCode Premium
    3. #433