Minimum Time to Visit a Cell In a Grid - Problem

You are given an m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].

You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.

Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.

Input & Output

Example 1 — Basic Grid Navigation
$ Input: grid = [[0,1,1],[2,3,1],[2,3,1]]
Output: 3
💡 Note: Start at (0,0) at time 0, move right to (0,1) at time 1, then down to (1,1) at time 3 (wait until time ≥3), finally right to (1,2) at time 3. Total time: 3.
Example 2 — Impossible Case
$ Input: grid = [[0,2],[2,2]]
Output: -1
💡 Note: Both adjacent cells (0,1) and (1,0) require time ≥2 to enter, but we can only reach them at time 1. Since we can't move anywhere from start, return -1.
Example 3 — Waiting Strategy
$ Input: grid = [[0,0,0],[0,0,5],[0,0,0]]
Output: 5
💡 Note: We can reach (1,2) by going around: (0,0) → (0,1) → (0,2) → (1,2), arriving at time 3, but cell requires time ≥5. We can wait by moving back and forth until time 5.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 2 ≤ m, n ≤ 1000
  • 0 ≤ grid[i][j] ≤ 105

Visualization

Tap to expand
Minimum Time to Visit Cell: Grid Navigation with Time Locks011231STARTENDOptimal Path Timelinet=0: Start at (0,0)t=1: Move to (0,1)t=3: Wait, then (1,1)t=3: Reach (1,2) ✓Answer: Minimum time = 3 seconds
Understanding the Visualization
1
Input Grid
Each cell shows minimum time required to enter
2
Path Finding
Find route from top-left to bottom-right
3
Time Calculation
Account for waiting periods and movement time
Key Takeaway
🎯 Key Insight: Use Dijkstra's algorithm to handle time constraints and waiting periods efficiently
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
23.5K Views
Medium Frequency
~35 min Avg. Time
892 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