Problem Description
Given an m x n grid where each cell grid[i][j] indicates the maximum number of steps you can move either rightward or downward from that cell, determine the minimum number of cells you need to visit to reach the bottom-right cell. If no valid path exists, return -1.
Key Insights
- Model the grid as a graph with nodes representing cells and edges representing valid moves.
- Use Breadth-First Search (BFS) to find the shortest path in an unweighted graph.
- To avoid TLE when many cells can be reached from each node, maintain pointers (or indices) that record how far you have already processed in each row and column. This prevents re‐exploration of previously scanned segments.
- Mark cells as visited to prevent redundant work.
Space and Time Complexity
Time Complexity: O(m * n) – Each cell is processed at most once using the controlled range scanning. Space Complexity: O(m * n) – For the BFS queue and auxiliary arrays for visited nodes.
Solution
We use a BFS approach starting from cell (0,0). For each cell (i, j) the grid value provides two ranges:
- Rightward moves: from column j+1 to min(n-1, j + grid[i][j])
- Downward moves: from row i+1 to min(m-1, i + grid[i][j]) To avoid checking the same segments repeatedly, we maintain two arrays:
- next_in_row[i]: the next unprocessed column in row i.
- next_in_col[j]: the next unprocessed row in column j. At each step, we update these pointers after processing the respective range and add newly reachable, unvisited cells to the BFS queue. The path length is tracked as the number of cells visited so far; when we reach the bottom-right, we return that count.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.