[LeetCode] Minimum Time to Visit a Cell In a Grid

2577. Minimum Time to Visit a Cell In a Grid

You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].

You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.

Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
int minimumTime(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
priority_queue<array<int,4>, vector<array<int,4>>, greater<array<int,4>>> q;
q.push({0,0,0,0});
vector<vector<vector<int>>> vis(n,vector<vector<int>>(m, vector<int>(2,INT_MAX)));
vis[0][0][0] = 0;
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
while(q.size()) {
auto[v, fl, y, x] = q.top();
q.pop();
if (vis[y][x][fl] != v) continue;
bool less = false;
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) {
if (A[ny][nx] <= v + 1) less = true;
}
}
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) {
if (A[ny][nx] <= v + 1) {
if (vis[ny][nx][!fl] > v + 1) {
vis[ny][nx][!fl] = v + 1;
q.push({vis[ny][nx][!fl], !fl, ny, nx});
}
} else if (less) {
int req = A[ny][nx] - (v + 1);
if (req & 1) req += 1;
req += 1;
if (vis[ny][nx][fl] > v + req) {
vis[ny][nx][fl] = v + req;
q.push({vis[ny][nx][fl], fl, ny, nx});
}
}
}
}
}

int res = min(vis[n-1][m-1][0], vis[n-1][m-1][1]);
return res == INT_MAX ? -1 : res;
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/26/PS/LeetCode/minimum-time-to-visit-a-cell-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.