3341. Find Minimum Time to Reach Last Room I.cpp #118
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Approach:
This solution also uses Dijkstra’s algorithm to find the minimum time to reach the destination cell.
Each cell (i, j) can only be entered after its given moveTime[i][j].
We use a priority queue to always expand the cell that can be reached at the earliest time.
Steps:
Start from (0, 0) at time 0.
Use a min-heap to process cells in order of increasing arrival time.
For each direction (up, down, left, right):
You can move to (nrow, ncol) only after moveTime[nrow][ncol].
The earliest time you can arrive there is max(curr, moveTime[nrow][ncol]) + 1.
If this time is smaller than the previously recorded distance, update it and push it into the heap.
Intuition:
Think of the grid as a map with time-locked cells — you can’t step on a cell before its allowed time.
Using Dijkstra ensures we always choose the minimum total time path considering both waiting (if the cell isn’t ready) and moving (which always costs +1).
It’s like finding the fastest route through a grid where some roads open later than others.
Solution in Code (C++)
class Solution {
public:
int minTimeToReach(vector<vector>& moveTime) {
int m = moveTime.size(), n = moveTime[0].size();
};