You are given a m × n integer matrix grid where you start at the top-left corner (0, 0) and need to reach the bottom-right corner (m-1, n-1).

From any cell (i, j), you can make strategic jumps based on the cell's value grid[i][j]:

  • Right jumps: Move to any cell (i, k) where j < k ≤ grid[i][j] + j
  • Down jumps: Move to any cell (k, j) where i < k ≤ grid[i][j] + i

Your goal is to find the minimum number of cells you need to visit to reach the destination. If no valid path exists, return -1.

Example: If you're at cell (0, 0) with value 3, you can jump right to columns 1, 2, 3 or down to rows 1, 2, 3 in the same column.

Input & Output

example_1.py — Basic Grid Traversal
$ Input: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]]
Output: 4
💡 Note: Starting from (0,0) with value 3, we can jump to (0,1), (0,2), (0,3), (1,0), (2,0), or (3,0). The optimal path is (0,0) → (0,2) → (3,2) → (3,3) requiring 4 cells to be visited.
example_2.py — Impossible Path
$ Input: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[2,4,0,0]]
Output: -1
💡 Note: From the starting position, we cannot reach the bottom-right corner due to the 0 values blocking our path. The cell (2,2) has value 1 which only allows movement to (2,3), but (2,3) has value 0 preventing further movement.
example_3.py — Single Cell
$ Input: grid = [[2]]
Output: 1
💡 Note: The grid has only one cell, so we're already at the destination. Only 1 cell needs to be visited.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m * n ≤ 105
  • 0 ≤ grid[i][j] < m * n
  • grid[m - 1][n - 1] == 0

Visualization

Tap to expand
Minimum Number of Visited Cells in a Grid INPUT 3 4 2 1 4 2 3 1 2 1 0 0 2 4 0 0 S E Jump Rules: Right: (i,j) to (i,k) where j < k <= grid[i][j]+j Down: (i,j) to (k,j) where i < k <= grid[i][j]+i grid = [[3,4,2,1], [4,2,3,1],[2,1,0,0], [2,4,0,0]] ALGORITHM (BFS) 1 Initialize BFS Start at (0,0), dist=1 Add to queue 2 Process Queue Pop cell, explore all reachable neighbors 3 Track Visited Mark cells visited Record min distance 4 Check Target If (m-1,n-1) reached Return distance BFS Traversal (0,0) (0,3) (3,0) (3,3) FINAL RESULT 3 4 2 1 4 2 3 1 2 1 0 0 2 4 0 0 Optimal Path: (0,0) --> (0,3) --> (1,3) --> (3,3) Output: 4 OK - 4 cells visited (minimum possible) Key Insight: BFS guarantees finding the shortest path in terms of number of cells visited. From each cell (i,j), we can jump RIGHT to any column k where j < k <= j + grid[i][j], or DOWN to any row k where i < k <= i + grid[i][j]. Level-by-level exploration ensures minimum steps when target is reached. TutorialsPoint - Minimum Number of Visited Cells in a Grid | BFS Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
67.4K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen