Skip to content

Commit 1e0caf8

Browse files
authored
Create 2577. Minimum Time to Visit a Cell In a Grid (#646)
2 parents 49b6b6a + 9fae4de commit 1e0caf8

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution {
2+
public:
3+
int minimumTime(vector<vector<int>>& grid) {
4+
5+
int m = grid.size();
6+
int n = grid[0].size();
7+
8+
vector<int> visited(m * n, -1);
9+
10+
priority_queue<pair<int, int>, vector<pair<int, int>>,
11+
greater<pair<int, int>>>
12+
q;
13+
14+
q.push({0, 0});
15+
visited[0] = 0;
16+
vector<int> dir = {0, -1, 0, 1, 0};
17+
18+
if (grid[1][0] > 1 && grid[0][1] > 1)
19+
return -1;
20+
21+
while (q.size() > 0) {
22+
23+
auto node = q.top();
24+
q.pop();
25+
26+
int row = node.second / n;
27+
int col = node.second % n;
28+
29+
int val = node.second;
30+
31+
int t = node.first;
32+
33+
if (row == m - 1 && col == n - 1) {
34+
return t;
35+
}
36+
for (int j = 0; j < 4; j++) {
37+
38+
int new_row = row + dir[j];
39+
int new_col = col + dir[j + 1];
40+
41+
if (new_row < 0 || new_row >= m || new_col < 0 || new_col >= n)
42+
continue;
43+
44+
int val = new_row * n + new_col;
45+
if (visited[val] != -1)
46+
continue;
47+
48+
if (grid[new_row][new_col] <= t + 1)
49+
visited[val] = t + 1;
50+
else if ((t + 1) % 2 != grid[new_row][new_col] % 2)
51+
visited[val] = grid[new_row][new_col] + 1;
52+
else
53+
visited[val] = grid[new_row][new_col];
54+
q.push({visited[val], val});
55+
}
56+
}
57+
58+
return -1;
59+
}
60+
};

0 commit comments

Comments
 (0)