312. Snakes and Ladders
You are given an n x n integer matrix board where the cells are labeled from 1 to n^2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr, do the following: - Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n^2)]. - If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. The game ends when you reach the square n^2. A board square on row r and column c has a snake or ladder if board[r][c] != -1. Return the least number of moves required to reach the square n^2. If it is not possible to reach the square, return -1.
Examples
Input: [[-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]]
Output: 4
Explanation: Square 1 -> 2 (ladder to 15) -> 17 -> 13 (ladder to 35) -> 36, four moves.
Constraints
- n == board.length == board[i].length
- 2 <= n <= 20
- grid[i][j] is either -1 or in the range [1, n^2].
- The squares labeled 1 and n^2 do not have any ladders or snakes.
Run checks all cases above. Submit evaluates all test cases.