3342. Find Minimum Time to Reach Last Room II.cpp#116
Open
shafaq16 wants to merge 1 commit intoSjxSubham:mainfrom
Open
3342. Find Minimum Time to Reach Last Room II.cpp#116shafaq16 wants to merge 1 commit intoSjxSubham:mainfrom
shafaq16 wants to merge 1 commit intoSjxSubham:mainfrom
Conversation
4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 problem uses Dijkstra’s algorithm on a grid to find the minimum time to reach the bottom-right cell from the top-left.
Each cell has a moveTime constraint — you can’t enter it before that time.
We use a min-heap (priority queue) to always expand the cell that can be reached earliest.
At each step:
Pop the cell with the smallest current time.
Try moving in all 4 directions (up, down, left, right).
For each neighbor:
Compute wait time = max(moveTime[i_][j_] - currTime, 0) (if we must wait before entering).
Compute move cost = 1 or 2 depending on cell parity (i_ + j_) % 2.
Update arrival time and push to the queue if it’s smaller than the previous best.
Intuition:
It’s like a weighted shortest path problem on a grid.
You can’t move into a cell before its “unlock time” (moveTime[i][j]), so you might need to wait.
Using Dijkstra ensures we always choose the earliest possible time to reach each cell while considering both waiting and moving costs efficiently.
Solution in Code(C++)
class Solution {
public:
vector<vector>directions{{1,0},{-1,0},{0,1},{0,-1}};
typedef pair<int,pair<int,int>>P;
int minTimeToReach(vector<vector>& moveTime) {
int m=moveTime.size(),n=moveTime[0].size();
};