Skip to content

Conversation

@shafaq16
Copy link
Contributor

@shafaq16 shafaq16 commented Oct 5, 2025

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

    priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<>> pq;
    pq.push({0, {0, 0}});

    vector<vector<int>> dis(m, vector<int>(n, INT_MAX));
    dis[0][0] = 0;

    int dir[5] = {-1, 0, 1, 0, -1};

    while (!pq.empty()) {
        auto [curr, pos] = pq.top(); pq.pop();
        int row = pos.first, col = pos.second;

        if (row == m - 1 && col == n - 1)
            return curr;

        for (int i = 0; i < 4; i++) {
            int nrow = row + dir[i], ncol = col + dir[i + 1];
            if (nrow >= 0 && ncol >= 0 && nrow < m && ncol < n) {
                int nextTime = max(curr, moveTime[nrow][ncol]) + 1;
                if (nextTime < dis[nrow][ncol]) {
                    dis[nrow][ncol] = nextTime;
                    pq.push({nextTime, {nrow, ncol}});
                }
            }
        }
    }

    return -1;
}

};

@SjxSubham
Copy link
Owner

U and others who contributed already are only allowed to solve only 2 issue...
Let's give chance to others as well...
#119 #118 #120

@SjxSubham SjxSubham closed this Oct 5, 2025
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.

2 participants