-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0743-network-delay-time.js
More file actions
67 lines (58 loc) · 1.89 KB
/
0743-network-delay-time.js
File metadata and controls
67 lines (58 loc) · 1.89 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
/**
* Network Delay Time
* Time Complexity: O(V^2 + E)
* Space Complexity: O(V + E)
*/
var networkDelayTime = function (times, n, k) {
const distanceToNode = new Array(n + 1).fill(Infinity);
distanceToNode[k] = 0;
const graphAdjacency = new Map();
for (const [sourceNodeValue, targetNodeValue, weightValue] of times) {
if (!graphAdjacency.has(sourceNodeValue)) {
graphAdjacency.set(sourceNodeValue, []);
}
graphAdjacency.get(sourceNodeValue).push([targetNodeValue, weightValue]);
}
const minPriorityQueue = [[0, k]];
while (minPriorityQueue.length > 0) {
let currentMinimumDistance = Infinity;
let currentNodeId = -1;
let minEntryIndex = -1;
for (
let loopIteratorOne = 0;
loopIteratorOne < minPriorityQueue.length;
loopIteratorOne++
) {
const [distVal, nodeIdVal] = minPriorityQueue[loopIteratorOne];
if (distVal < currentMinimumDistance) {
currentMinimumDistance = distVal;
currentNodeId = nodeIdVal;
minEntryIndex = loopIteratorOne;
}
}
minPriorityQueue.splice(minEntryIndex, 1);
if (currentMinimumDistance > distanceToNode[currentNodeId]) {
continue;
}
if (graphAdjacency.has(currentNodeId)) {
for (const [neighborId, edgeWeightToNeighbor] of graphAdjacency.get(
currentNodeId,
)) {
const newCalculatedDistance =
currentMinimumDistance + edgeWeightToNeighbor;
if (newCalculatedDistance < distanceToNode[neighborId]) {
distanceToNode[neighborId] = newCalculatedDistance;
minPriorityQueue.push([newCalculatedDistance, neighborId]);
}
}
}
}
let resultTime = 0;
for (let nodeIterator = 1; nodeIterator <= n; nodeIterator++) {
if (distanceToNode[nodeIterator] === Infinity) {
return -1;
}
resultTime = Math.max(resultTime, distanceToNode[nodeIterator]);
}
return resultTime;
};