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:
4
💡 Note:
Start at (0,0) at time 0, move right to (0,1) at time 1, then right to (0,2) at time 2, then down to (1,2) at time 3, finally down to (2,2) at time 4. Total time: 4.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code