Problem Description
You are given an n x n board where each cell contains either -1 or a destination number indicating a snake or ladder. The board cells are labeled from 1 to n² in a boustrophedon (alternating) manner starting from the bottom-left corner. From a current square, you roll a standard six-sided die, moving between 1 and 6 steps ahead. If you land on a cell with a snake or ladder (i.e. its value is not -1), you must take it, which may immediately change your position. Your goal is to determine the minimum number of dice rolls required to reach square n²; if it is impossible to reach, return -1.
Key Insights
- Use Breadth-First Search (BFS) to explore all possible moves from the start while tracking the number of dice rolls.
- Convert the one-dimensional square number into board coordinates accounting for the alternating direction in each row.
- When landing on a snake or ladder, follow it immediately, but only take one jump per roll.
- Maintain a visited set or array to avoid re-processing cells and prevent infinite loops.
Space and Time Complexity
Time Complexity: O(n²) – each of the n² cells is processed at most once during the BFS. Space Complexity: O(n²) – used for the queue and visited set to store positions.
Solution
The problem is solved via a Breadth-First Search (BFS) approach. Starting from square 1, we explore all reachable squares (up to six moves ahead) for each dice roll. For each move, we convert the square number into board coordinates while considering the alternating order of rows. When a move encounters a snake or ladder (board value not equal to -1), we move directly to its destination. By using BFS, we ensure that the first time we reach the final square (n²) it is with the fewest moves possible. To guarantee no repeated work, we track visited squares.