-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11.js
76 lines (65 loc) · 1.61 KB
/
11.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* @param {number} n
* @param {number[][]} edges
*/
var Graph = function(n, edges) {
this.map = new Map()
let map = this.map;
for(let i = 0; i < edges.length; i++){
let edge = edges[i]
let from = edge[0]
let to = edge[1]
let cost = edge[2]
if(!map.has(from)){
map.set(from, new Set())
}
map.get(from).add({to, cost})
}
};
/**
* @param {number[]} edge
* @return {void}
*/
Graph.prototype.addEdge = function(edge) {
let map = this.map;
let from = edge[0]
let to = edge[1]
let cost = edge[2]
if(!map.has(from)){
map.set(from, new Set())
}
map.get(from).add({to, cost})
};
/**
* @param {number} node1
* @param {number} node2
* @return {number}
*/
Graph.prototype.shortestPath = function(node1, node2) {
const heap = new MinPriorityQueue()
heap.enqueue({node: node1, cost: 0}, 0)
let visited = new Set()
while(heap.size() > 0){
const top = heap.dequeue().element;
if(visited.has(top.node)){
continue;
}
visited.add(top.node)
if(top.node === node2){
return top.cost;
}
let next = this.map.get(top.node)
if(next){
for (let n of next){
heap.enqueue({node: n.to, cost: top.cost + n.cost}, top.cost + n.cost)
}
}
}
return -1
};
/**
* Your Graph object will be instantiated and called as such:
* var obj = new Graph(n, edges)
* obj.addEdge(edge)
* var param_2 = obj.shortestPath(node1,node2)
*/