Problem
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
nextwith a label in the range[curr + 1, min(curr + 6, n^2)].- This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
- If
nexthas a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move tonext. - 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. The destination of that snake or ladder is board[r][c]. Squares 1 and n^2 do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.
- For example, suppose the board is
[[-1,4],[-1,3]], and on the first move, your destination square is2. You follow the ladder to square3, but do not follow the subsequent ladder to4.
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
Example 1:
| |
Example 2:
| |
Solution
Method 1 - BFS
This approach efficiently solves the problem using BFS to find the minimum number of moves required to navigate from square 1 to square n^2 in a Boustrophedon-style board.
Here is approach:
- Label Conversion:
- We need a way to convert from the linear square number (1 to (n^2)) to the 2D coordinates on the board.
- Breadth-First Search (BFS):
- We start at square
1and explore all possible next moves (up to 6 moves forward). - Keep track of visited squares to avoid cycles.
- We start at square
- Snakes and Ladders:
- If a move lands on a square with a snake/ladder, directly move to the destination specified by that square.
- Termination:
- The search ends once we reach square (n^2).
Here are the steps we can follow:
- Use a queue to perform BFS, starting from square
1. - For each square, calculate all possible next moves (from 1 to 6 steps forward).
- Apply any snake or ladder effects.
- Continue until reaching (n^2) or exhausting all possible moves.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n^2), where (n) is the dimension of the board. Each node (square) can be visited once, and each node has at most 6 neighboring nodes. - 🧺 Space complexity:
O(n^2), due to the queue and visited set.