[LeetCode] Find Minimum Time to Reach Last Room II

3342. Find Minimum Time to Reach Last Room II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
int n = moveTime.size(), m = moveTime[0].size();
vector<vector<int>> dp(n, vector<int>(m,INT_MAX));
map<int,queue<array<int,3>>> mq;
auto push = [&](int y, int x, int c) {
if(dp[y][x] > c) {
dp[y][x] = c;
mq[c].push({c,y,x});
}
};
push(0,0,0);
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
while(mq.size()) {
auto& q = begin(mq)->second;
while(q.size()) {
auto [c,y,x] = q.front(); q.pop();
if(dp[y][x] != c) continue;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m) {
int cost = max(c, moveTime[ny][nx]) + ((ny + nx) % 2 ? 1 : 2);
push(ny,nx,cost);
}
}
}
mq.erase(begin(mq));
}

return dp[n-1][m-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/03/PS/LeetCode/find-minimum-time-to-reach-last-room-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.