|
| 1 | +/** |
| 2 | + * Title: Design Graph with Shortest Path Calculator |
| 3 | + * Description: There is a directed weighted graph that consists of n nodes numbered from 0 to n - 1. The edges of the graph are initially represented by the given array edges where edges[i] = [fromi, toi, edgeCosti] meaning that there is an edge from fromi to toi with the cost edgeCosti. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 04/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number} n |
| 10 | + * @param {number[][]} edges |
| 11 | + */ |
| 12 | +var Graph = function (n, edges) { |
| 13 | + this.map = new Map(); |
| 14 | + let map = this.map; |
| 15 | + for (let i = 0; i < edges.length; i++) { |
| 16 | + let edge = edges[i]; |
| 17 | + let from = edge[0]; |
| 18 | + let to = edge[1]; |
| 19 | + let cost = edge[2]; |
| 20 | + if (!map.has(from)) { |
| 21 | + map.set(from, new Set()); |
| 22 | + } |
| 23 | + |
| 24 | + map.get(from).add({ to, cost }); |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {number[]} edge |
| 30 | + * @return {void} |
| 31 | + */ |
| 32 | +Graph.prototype.addEdge = function (edge) { |
| 33 | + let map = this.map; |
| 34 | + let from = edge[0]; |
| 35 | + let to = edge[1]; |
| 36 | + let cost = edge[2]; |
| 37 | + if (!map.has(from)) { |
| 38 | + map.set(from, new Set()); |
| 39 | + } |
| 40 | + |
| 41 | + map.get(from).add({ to, cost }); |
| 42 | +}; |
| 43 | + |
| 44 | +/** |
| 45 | + * @param {number} node1 |
| 46 | + * @param {number} node2 |
| 47 | + * @return {number} |
| 48 | + */ |
| 49 | +Graph.prototype.shortestPath = function (node1, node2) { |
| 50 | + const heap = new MinPriorityQueue(); |
| 51 | + heap.enqueue({ node: node1, cost: 0 }, 0); |
| 52 | + let visited = new Set(); |
| 53 | + |
| 54 | + while (heap.size() > 0) { |
| 55 | + const top = heap.dequeue().element; |
| 56 | + |
| 57 | + if (visited.has(top.node)) { |
| 58 | + continue; |
| 59 | + } |
| 60 | + visited.add(top.node); |
| 61 | + if (top.node === node2) { |
| 62 | + return top.cost; |
| 63 | + } |
| 64 | + let next = this.map.get(top.node); |
| 65 | + if (next) { |
| 66 | + for (let n of next) { |
| 67 | + heap.enqueue( |
| 68 | + { node: n.to, cost: top.cost + n.cost }, |
| 69 | + top.cost + n.cost |
| 70 | + ); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return -1; |
| 76 | +}; |
| 77 | + |
| 78 | +/** |
| 79 | + * Your Graph object will be instantiated and called as such: |
| 80 | + * var obj = new Graph(n, edges) |
| 81 | + * obj.addEdge(edge) |
| 82 | + * var param_2 = obj.shortestPath(node1,node2) |
| 83 | + */ |
0 commit comments