-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1514-path-with-maximum-probability.js
50 lines (46 loc) · 1.27 KB
/
1514-path-with-maximum-probability.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
/**
* @param {number} n
* @param {number[][]} edges
* @param {number[]} succProb
* @param {number} start
* @param {number} end
* @return {number}
*/
var maxProbability = function(n, edges, succProb, start, end) {
const genAdjList = () => {
/***
{
0: [[1, 0.5], [2, 0.2]],
1: [[0, 0.5], [2, 0.5]],
2: [[1, 0.5], [0, 0.2]],
}
***/
let list = {};
for(let i = 0; i < n; i++) {
list[i] = [];
}
for(let i = 0; i < edges.length; i++) {
const [v1, v2] = edges[i];
const p = succProb[i];
list[v1].push([v2, p]);
list[v2].push([v1, p]);
}
return list;
}
const graph = genAdjList();
const queue = new MaxPriorityQueue();
const visited = new Set();
queue.enqueue([start, 1], 1);
while(!queue.isEmpty()) {
const [n1, p1] = queue.dequeue().element;
if(visited.has(n1)) continue;
visited.add(n1);
if(n1 === end) return p1;
for(const [n2, p2] of graph[n1]) {
if(visited.has(n2)) continue;
const val = p1 * p2;
queue.enqueue([n2, val], val);
}
}
if(visited.size !== n) return 0;
};