-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork_Delay_Time.cpp
More file actions
74 lines (61 loc) · 2.12 KB
/
Copy pathNetwork_Delay_Time.cpp
File metadata and controls
74 lines (61 loc) · 2.12 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <vector>
#include <queue>
#include <limits.h>
struct compare {
bool operator()(std::pair<int, int> a, std::pair<int, int> b) {
return a.second > b.second;
}
};
class Solution {
public:
// Djikstra's
int networkDelayTime(std::vector<std::vector<int>>& times, int n, int k) {
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, compare> q;
std::vector<std::vector<std::pair<int, int>>> adjacencyList(n+1, std::vector<std::pair<int, int>>(0));
std::vector<int> visited(n+1, -1);
std::vector<int> distances(n+1, INT_MAX);
distances[0] = 0;
distances[k] = 0;
// Create adjacency list representation of the network
for (int i=0; i<times.size(); i++) {
adjacencyList[times[i][0]].push_back({times[i][1], times[i][2]});
}
// Push starting node into the queue
q.push({k, 0});
int numVisited = 0;
while (!q.empty()) {
std::pair<int, int> curr = q.top();
q.pop();
if (visited[curr.first] == 0) {
continue;
}
// mark node as visited
visited[curr.first] = 0;
numVisited++;
if (numVisited == n) {
break;
}
// loop through all adjacent nodes
std::vector<std::pair<int, int>> neighbours = adjacencyList[curr.first];
for (int i=0; i<neighbours.size(); i++) {
int distance = curr.second + neighbours[i].second;
if (distance < distances[neighbours[i].first]) {
distances[neighbours[i].first] = distance;
q.push({neighbours[i].first, distance});
}
}
}
// Find the greatest element out of all the distances
int answer = INT_MIN;
for (int i=0; i<distances.size(); i++) {
if (distances[i] > answer) {
answer = distances[i];
}
}
if (answer == INT_MAX) {
return -1;
} else {
return answer;
}
}
};