Skip to content

Commit

Permalink
Create 743-Network-Delay-Time.js
Browse files Browse the repository at this point in the history
Dijkstra's with a Min-Heap in JavaScript, with the same pattern as the YouTube video. 😁
  • Loading branch information
Samuel-Hinchliffe committed Jul 25, 2022
1 parent 3ea4354 commit f30ef10
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions javascript/743-Network-Delay-Time.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* @param {number[][]} times
* @param {number} n
* @param {number} k
* @return {number}
*/
var networkDelayTime = function (times, n, k) {

let time_taken = 0;
const visited_set = new Set();
const min_heap = new MinPriorityQueue();
const node_edge_cost = new Map();

for (const [node, edge, cost] of times) {
let edges = [];
if (node_edge_cost.has(node)) {
edges = node_edge_cost.get(node);
}
edges.push([edge, cost]);
node_edge_cost.set(node, edges);
}

min_heap.enqueue([k, 0], 0);

while (min_heap.size()) {

const [node, cost] = min_heap.dequeue().element;

if (visited_set.has(node)) continue;
visited_set.add(node);

time_taken = Math.max(cost, time_taken);

const node_edges = node_edge_cost.get(node) || [];

for (const [edge_node, edge_cost] of node_edges) {
if (!visited_set.has(edge_node)) {
min_heap.enqueue([edge_node, edge_cost + cost], edge_cost + cost);
}
}
}

return visited_set.size === n ? time_taken : -1;
};

0 comments on commit f30ef10

Please sign in to comment.