Skip to content

Snakes and Ladders

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

A square board board of size n x n holds the squares 1 to n². Numbering starts at the bottom-left corner and runs along each row, switching direction on every row, like this for n = 4:

16 15 14 13
 9 10 11 12
 8  7  6  5
 1  2  3  4

If the cell for square s holds -1, it is a plain square. Any other value is the square a snake or ladder sends you to.

You start on square 1. Each move, you roll a die and pick any square from s + 1 to min(s + 6, n²). If that square has a snake or ladder, you must follow it, but you follow at most one per move, even if it lands you on the start of another. Return the fewest moves to reach square n², or -1 if you can never reach it.

board = [[-1, -1, -1, -1],
         [-1, -1, -1, -1],
         [-1, -1, -1, -1],
         [-1, -1, 14, -1]]   →  2   (roll to 3, climb to 14, roll to 16)

Constraints

  • 2 <= n <= 20
  • board[i][j] is -1 or a square number from 1 to n².
  • Squares 1 and n² never hold a snake or ladder.