[LeetCode] Find Minimum Time to Reach Last Room I

3341. Find Minimum Time to Reach Last Room I

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 exactly one second.

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
class Solution {
public:
int minTimeToReach(vector<vector<int>>& moveTime) {
int n = moveTime.size(), m = moveTime[0].size();
vector<vector<int>> cost(n, vector<int>(m,INT_MAX));
cost[0][0] = 0;
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
queue<pair<int,int>> q; q.push({0,0});
while(q.size()) {
auto [y,x] = q.front(); q.pop();
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 nc = max(cost[y][x] + 1,moveTime[ny][nx] + 1);
if(cost[ny][nx] > nc) {
cost[ny][nx] = nc;
q.push({ny,nx});
}
}
}
}
return cost[n-1][m-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/03/PS/LeetCode/find-minimum-time-to-reach-last-room-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.