-
Notifications
You must be signed in to change notification settings - Fork 0
/
743_Network_Delay_Time.js
53 lines (45 loc) · 1.13 KB
/
743_Network_Delay_Time.js
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
const networkDelayTime = (times, n, k) => {
const dijkstra = (graph, start, _end) => {
let priorityQueue = [[0, start]];
let map = {};
while (priorityQueue.length !== 0) {
const [cost, u] = priorityQueue.pop();
if (map[u] !== undefined) {
continue;
}
map[u] = cost;
if (graph[u] !== undefined) {
for (let [v, c] of graph[u]) {
if (map[v] !== undefined) {
continue;
}
let next = cost + c;
priorityQueue.push([next, v]);
priorityQueue.sort((a, b) => {
if (a[0] === b[0]) {
return b[1] - a[1];
} else {
return b[0] - a[0];
}
});
}
}
}
return map;
};
let graph = {};
for (let [from, to, cost] of times) {
if (graph[from - 1] !== undefined) {
graph[from - 1].push([to - 1, cost]);
} else {
graph[from - 1] = [[to - 1, cost]];
}
}
let dist = dijkstra(graph, k - 1, n);
let values = Object.values(dist);
if (values.length !== n) {
return -1;
} else {
return Math.max(...values);
}
};