-
Notifications
You must be signed in to change notification settings - Fork 0
/
743. Network Delay Time.cpp
52 lines (41 loc) · 1.6 KB
/
743. Network Delay Time.cpp
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
48
49
50
51
52
class Solution {
public:
vector<pair<int, int>> adj[101];
void dijkstra(vector<int>& signalReceivedAt, int source, int n) {
priority_queue<pair<int, int>, vector<pair<int, int>>,
greater<pair<int, int>>> pq;
pq.push({0, source});
signalReceivedAt[source] = 0;
while (!pq.empty()) {
int currNodeTime = pq.top().first;
int currNode = pq.top().second;
pq.pop();
if (currNodeTime > signalReceivedAt[currNode]) {
continue;
}
for (pair<int, int> edge : adj[currNode]) {
int time = edge.first;
int neighborNode = edge.second;
if (signalReceivedAt[neighborNode] > currNodeTime + time) {
signalReceivedAt[neighborNode] = currNodeTime + time;
pq.push({signalReceivedAt[neighborNode], neighborNode});
}
}
}
}
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
for (vector<int> time : times) {
int source = time[0];
int dest = time[1];
int travelTime = time[2];
adj[source].push_back({travelTime, dest});
}
vector<int> signalReceivedAt(n + 1, INT_MAX);
dijkstra(signalReceivedAt, k, n);
int answer = INT_MIN;
for (int i = 1; i <= n; i++) {
answer = max(answer, signalReceivedAt[i]);
}
return answer == INT_MAX ? -1 : answer;
}
};