A square board of n × n squares is numbered from 1 in the bottom-left corner: along the bottom row, then back along the next row, like a snake. Some squares start a ladder or a snake that moves you to another square. You start on square 1, and one move is a roll of a die: you go 1 to 6 squares ahead and, if you land where a ladder or a snake starts, follow it (only one per move). Find the fewest moves to reach square n × n, or -1 if you never can. Our example: a 4 × 4 board with a ladder from 2 to 11 and a snake from 14 to 4 — the answer is 2.
our board, 4 × 4
16goal
15
14↓ 4snake down to 4
13
9
10
11
12
8
7
6
5
1start
2↑ 11ladder up to 11
3
4
ladder 2 → 11, upsnake 14 → 4, down1 is at the bottom left; each row runs the other way from the one below
input
board: an n × n board. Its squares are numbered from 1 to n² from the bottom left corner, row by row upwards, and each row runs the other way from the one below it. board[r][c] is -1, or the square where the snake or ladder that starts on this square leads.
returns
The fewest moves from square 1 to square n². A move goes from square s to any of the squares s + 1 … min(s + 6, n²), as a die would roll; if a snake or a ladder starts there, it goes on to its end. Only one per move: a snake or a ladder that starts at the end is not taken. -1 if square n² cannot be reached.
constraints
2 ≤ n = board.length ≤ 20
board[i].length = n: the board is square
board[i][j] is −1 or 1 ≤ board[i][j] ≤ n²
no snake or ladder starts on squares 1 and n²
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.