|
| 1 | +/** |
| 2 | + * Title: Path with Maximum Probability |
| 3 | + * Description: You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 04/05/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * @param {number} n |
| 10 | + * @param {number[][]} edges |
| 11 | + * @param {number[]} succProb |
| 12 | + * @param {number} start |
| 13 | + * @param {number} end |
| 14 | + * @return {number} |
| 15 | + */ |
| 16 | +var maxProbability = function (n, edges, succProb, start, end) { |
| 17 | + const nei = [...Array(n)].map(() => []); |
| 18 | + |
| 19 | + for (let i = 0; i < edges.length; i++) { |
| 20 | + const [a, b] = edges[i]; |
| 21 | + nei[a].push([b, succProb[i]]); |
| 22 | + nei[b].push([a, succProb[i]]); |
| 23 | + } |
| 24 | + |
| 25 | + const probs = new Array(n).fill(0); |
| 26 | + let queue = [start]; |
| 27 | + probs[start] = 1; |
| 28 | + |
| 29 | + while (queue.length) { |
| 30 | + let next = []; |
| 31 | + for (let i of queue) { |
| 32 | + for (let [j, p] of nei[i]) { |
| 33 | + if (probs[i] * p > probs[j]) { |
| 34 | + next.push(j); |
| 35 | + probs[j] = probs[i] * p; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + queue = next; |
| 40 | + } |
| 41 | + |
| 42 | + return probs[end]; |
| 43 | +}; |
0 commit comments