Skip to content

Commit

Permalink
feat(book/pq): add exercise with pq and dijkstra
Browse files Browse the repository at this point in the history
  • Loading branch information
amejiarosario committed Sep 8, 2020
1 parent f248e42 commit 3a2a24f
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 21 deletions.
67 changes: 48 additions & 19 deletions book/interview-questions/network-delay-time.js
@@ -1,28 +1,57 @@
// https://leetcode.com/problems/network-delay-time/solution/
function networkDelayTime(times: number[][], N: number, K: number): number {
const graph = new Map<number, [number, number][]>(Array(N).fill(0).map((_, i) => [i + 1, []]));
times.forEach(([u, v, w]) => graph.get(u)?.push([v, w]));
const { PriorityQueue, Queue } = require('../../src/index');

const queue = new Queue([[K, 0]]);
const seen = Array(N + 1).fill(Infinity);
// tag::description[]
function networkDelayTime(times, N, K) {
// end::description[]
// tag::placeholder[]
// write your code here...
// end::placeholder[]
// tag::solution[]
const graph = new Map(Array(N).fill(0).map((_, i) => [i + 1, []]));
times.forEach(([u, v, w]) => graph.get(u).push([v, w]));

while (queue.size()) {
const [node, dist] = queue.dequeue();
seen[node] = Math.min(seen[node], dist);
const q = new PriorityQueue([[0, K]]);
const dist = new Map();

for (const [adj, w] of graph.get(node) || []) {
if (seen[adj] > dist + w) queue.enqueue([adj, dist + w]);
while (q.size) {
const [d, n] = q.dequeue();

if (dist.has(n)) continue;
dist.set(n, d);

for (const [adj, w] of graph.get(n)) {
if (!dist.has(adj)) q.enqueue([d + w, adj]);
}
}

const max = Math.max(...seen.slice(1));
return max === Infinity ? -1 : max;
};
return dist.size === N ? Math.max(...dist.values()) : -1;
// end::solution[]
// tag::description[]
}
// end::description[]

// tag::networkDelayTimeQueue[]
function networkDelayTimeQueue(times, N, K) {
const graph = new Map(Array(N).fill(0).map((_, i) => [i + 1, []]));
times.forEach(([u, v, w]) => graph.get(u).push([v, w]));

const q = new Queue([[0, K]]);
const dist = new Map();

/*
[[2,1,1],[2,3,1],[3,4,1]]
4
2
while (q.size) {
const [d, n] = q.dequeue();

dist.set(n, dist.has(n) ? Math.min(dist.get(n), d) : d);

for (const [adj, w] of graph.get(n)) {
if (!dist.has(adj) || dist.get(adj) > d + w) {
q.enqueue([d + w, adj]);
}
}
}

return dist.size === N ? Math.max(...dist.values()) : -1;
}
// end::networkDelayTimeQueue[]

*/
module.exports = { networkDelayTime, networkDelayTimeQueue };
47 changes: 45 additions & 2 deletions book/interview-questions/network-delay-time.spec.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 3a2a24f

Please sign in to comment.