Skip to content

Conversation

@shafaq16
Copy link
Contributor

@shafaq16 shafaq16 commented Oct 5, 2025

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();

    priority_queue<P,vector<P>,greater<P>>pq;
    vector<vector<int>>result(m,vector<int>(n,INT_MAX));

    result[0][0]=0;
    pq.push({0,{0,0}});

    while(!pq.empty()){
        int currTime=pq.top().first;
        auto cell=pq.top().second;

        int i=cell.first;
        int j=cell.second;

        pq.pop();
        if(i==m-1 && j==n-1) return currTime;

        for(auto &dir:directions){
            int i_=i+dir[0];
            int j_=j+dir[1];

            if(i_>=0 && i_<m && j_>=0 && j_<n){
                int moveCost=(i_+j_)%2==0?2:1;
                int wait=max(moveTime[i_][j_]-currTime,0);
                int arrTime=currTime+wait+moveCost;

                if(result[i_][j_]>arrTime){
                    result[i_][j_]=arrTime;
                    pq.push({arrTime,{i_,j_}});
                }
            }
        }
    }
    return -1;
}

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant