Skip to content

Commit 3bb23f6

Browse files
Update 3341. Find Minimum Time to Reach Last Room I.cpp
1 parent 88c4337 commit 3bb23f6

File tree

1 file changed

+41
-50
lines changed

1 file changed

+41
-50
lines changed
Lines changed: 41 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,44 @@
1-
#include <bits/stdc++.h>
2-
using namespace std;
3-
using ll = long long;
4-
struct Node {
5-
int r, c;
6-
ll t;
7-
};
8-
struct Cmp {
9-
bool operator()(const Node &a, const Node &b) const {
10-
return a.t > b.t;
11-
}
12-
};
13-
ll minTimeToReach(vector<vector<ll>>& moveTime) {
14-
int n = moveTime.size();
15-
int m = moveTime[0].size();
16-
const ll INF = LLONG_MAX / 4;
17-
vector<vector<ll>> dist(n, vector<ll>(m, INF));
18-
priority_queue<Node, vector<Node>, Cmp> pq;
19-
dist[0][0] = 0;
20-
pq.push({0, 0, 0});
21-
int dr[4] = {1, -1, 0, 0};
22-
int dc[4] = {0, 0, 1, -1};
23-
while (!pq.empty()) {
24-
Node cur = pq.top();
25-
pq.pop();
26-
if (cur.t > dist[cur.r][cur.c]) continue;
27-
if (cur.r == n - 1 && cur.c == m - 1) return cur.t;
28-
for (int i = 0; i < 4; i++) {
29-
int nr = cur.r + dr[i];
30-
int nc = cur.c + dc[i];
31-
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
32-
ll arrival = max(moveTime[nr][nc], cur.t) + 1;
33-
if (arrival < dist[nr][nc]) {
34-
dist[nr][nc] = arrival;
35-
pq.push({nr, nc, arrival});
36-
}
1+
class Solution {
2+
public:
3+
struct Node {
4+
int r, c, t;
5+
};
6+
7+
struct Cmp {
8+
bool operator()(const Node &a, const Node &b) const {
9+
return a.t > b.t;
3710
}
38-
}
39-
return dist[n - 1][m - 1];
40-
}
41-
int main() {
42-
int n, m;
43-
cin >> n >> m;
44-
vector<vector<ll>> moveTime(n, vector<ll>(m));
45-
for (int i = 0; i < n; i++) {
46-
for (int j = 0; j < m; j++) {
47-
cin >> moveTime[i][j];
11+
};
12+
13+
int minTimeToReach(vector<vector<int>>& moveTime) {
14+
int n = moveTime.size();
15+
int m = moveTime[0].size();
16+
const int INF = INT_MAX / 2;
17+
vector<vector<int>> dist(n, vector<int>(m, INF));
18+
priority_queue<Node, vector<Node>, Cmp> pq;
19+
dist[0][0] = 0;
20+
pq.push({0, 0, 0});
21+
int dr[4] = {1, -1, 0, 0};
22+
int dc[4] = {0, 0, 1, -1};
23+
24+
while (!pq.empty()) {
25+
Node cur = pq.top();
26+
pq.pop();
27+
if (cur.t > dist[cur.r][cur.c]) continue;
28+
if (cur.r == n - 1 && cur.c == m - 1) return cur.t;
29+
30+
for (int i = 0; i < 4; i++) {
31+
int nr = cur.r + dr[i];
32+
int nc = cur.c + dc[i];
33+
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
34+
int arrival = max(moveTime[nr][nc], cur.t) + 1;
35+
if (arrival < dist[nr][nc]) {
36+
dist[nr][nc] = arrival;
37+
pq.push({nr, nc, arrival});
38+
}
39+
}
4840
}
41+
42+
return -1;
4943
}
50-
ll res = minTimeToReach(moveTime);
51-
cout << res << "\n";
52-
return 0;
53-
}
44+
};

0 commit comments

Comments
 (0)