Skip to content
Decoder

Snakes and Ladders

Medium

Problem

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:

Example 1

16 15 14 13

Example 2

 9 10 11 12

Example 3

 8  7  6  5

Example 4

 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.

Example 5

board = [[-1, -1, -1, -1],

Example 6

         [-1, -1, -1, -1],

Example 7

         [-1, -1, -1, -1],

Example 8

Input
[-1, -1, 14, -1]]
Output
2
Why
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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.