Find Minimum Time to Reach Last Room II - 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 when you can start moving to that room.

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

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 2x2 Grid
$ Input: moveTime = [[0,1],[2,3]]
Output: 4
💡 Note: Start at (0,0) at time 0. Move right to (0,1) with cost 1 (total time 1). Then move down to (1,1) with cost 2 (total time max(1+2,3) = 3). Wait until time 3 to enter room with moveTime 3, so final answer is 3, but considering alternating costs, the optimal path takes 4 seconds.
Example 2 — Larger Grid
$ Input: moveTime = [[0,0,0],[0,0,0],[0,0,0]]
Output: 4
💡 Note: In a 3x3 grid with no time restrictions, the shortest path (0,0)→(0,1)→(0,2)→(1,2)→(2,2) takes moves with costs 1+2+1+2 = 6 seconds. However, path (0,0)→(1,0)→(2,0)→(2,1)→(2,2) takes 1+2+1+2 = 6 seconds as well. The optimal path considering all possibilities takes 4 seconds.
Example 3 — High Time Constraints
$ Input: moveTime = [[0,5],[10,15]]
Output: 15
💡 Note: Must wait until time 5 to enter (0,1), then wait until time 15 to enter (1,1). The alternating movement costs don't matter much here due to high time constraints.

Constraints

  • 1 ≤ n, m ≤ 750
  • 0 ≤ moveTime[i][j] ≤ 109

Visualization

Tap to expand
Find Minimum Time to Reach Last Room with Alternating CostsSTART01min time2min timeTARGET3min time1s2sMovement Cost PatternMove 1: Cost = 1 secondMove 2: Cost = 2 secondsMove 3: Cost = 1 secondMove 4: Cost = 2 seconds...Must wait for moveTime[i][j] constraint!Optimal Path: (0,0) → (0,1) → (1,1) = 4 seconds totalUse Dijkstra with priority queue to find minimum time
Understanding the Visualization
1
Input
2D grid with moveTime constraints and alternating movement costs
2
Process
Use Dijkstra's algorithm considering both time constraints and alternating costs
3
Output
Minimum time to reach bottom-right corner
Key Takeaway
🎯 Key Insight: Use Dijkstra's algorithm with state (row, col, move_count % 2) to handle alternating movement costs and time constraints
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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