Find Minimum Time to Reach Last Room I - Problem

There is a dungeon with n x m rooms arranged as a grid. You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum time in seconds after which the room opens and can be moved to.

You start from the room (0, 0) at time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes exactly one second.

Return the minimum time to reach the room (n - 1, m - 1).

Two rooms are adjacent if they share a common wall, either horizontally or vertically.

Input & Output

Example 1 — Basic Grid
$ Input: moveTime = [[0,1,1],[1,1,1]]
Output: 3
💡 Note: Start at (0,0) at time 0 → move to (0,1) at time 1 → move to (1,1) at time 3 (wait until room opens). Total time: 3 seconds.
Example 2 — Blocked Path
$ Input: moveTime = [[0,2,99],[1,1,1]]
Output: 5
💡 Note: Path: (0,0) t=0 → (1,0) t=1 → (1,1) t=2 → (0,1) t=3 (wait) → (1,1) t=5. Need to alternate to reach time 2 for (0,1).
Example 3 — Simple Path
$ Input: moveTime = [[0,1],[2,3]]
Output: 3
💡 Note: Direct path: (0,0) t=0 → (0,1) t=1 → (1,1) t=3 (wait for room to open at time 3). Total: 3 seconds.

Constraints

  • 2 ≤ n, m ≤ 750
  • n == moveTime.length
  • m == moveTime[i].length
  • 0 ≤ moveTime[i][j] ≤ 109

Visualization

Tap to expand
Find Minimum Time to Reach Last Room I INPUT moveTime Grid (2x3) 0 START 1 1 1 1 1 END (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) Input Array: [[0,1,1],[1,1,1]] n=2, m=3 Rules: - Start at (0,0) at t=0 - Move takes 1 second - Wait if room not open - Reach (n-1, m-1) ALGORITHM STEPS 1 Initialize Dijkstra dist[0][0]=0, others=INF Priority queue with (0,0,0) 2 Process Each Room Pop min time from queue Check 4 adjacent rooms 3 Calculate Arrival Time wait = max(curr, moveTime) arrival = wait + 1 4 Update and Continue If better, update dist Push to priority queue Optimal Path Trace: t=0 (0,0) --> t=1 (0,1) --> t=2 (0,2) --> t=3 (1,2) t=0: Start | t=1: (0,1) open at 1 t=2: (0,2) open at 1 | t=3: (1,2) done Time Complexity: O(nm log(nm)) FINAL RESULT Shortest Path Found: 0 t=0 1 t=1 1 t=2 1 1 1 t=3 OUTPUT 3 OK - Verified Minimum time = 3 seconds Path: (0,0) --> (0,1) --> (0,2) --> (1,2) No waiting needed on this path Key Insight: This is a modified shortest path problem where we must consider room opening times. Use Dijkstra's algorithm with a priority queue. For each move, the arrival time is max(current_time, moveTime[next]) + 1. We may need to wait at current position if the next room hasn't opened yet. Greedy BFS won't work here! TutorialsPoint - Find Minimum Time to Reach Last Room I | Optimal Solution (Dijkstra's Algorithm)
Asked in
Google 15 Amazon 12 Meta 8 Apple 6
12.5K Views
Medium Frequency
~25 min Avg. Time
234 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