[LeetCode] Path with Maximum Probability

1514. Path with Maximum Probability

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].

Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.

If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

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
class Solution {
int getParent(vector<int>& g, int n) {
return g[n] == n ? n : g[n] = getParent(g, g[n]);
}
void merge(vector<int>& g, int a, int b) {
int pa = getParent(g, a), pb = getParent(g, b);
if(pa > pb) swap(pa, pb);
g[pa] = g[pb] = pa;
}
public:
double maxProbability(int n, vector<vector<int>>& e, vector<double>& s, int start, int end) {
vector<double> dp(n);
vector<int> unionFind(n);
map<int, vector<pair<int, double>>> gr;
for(int i = 0; i < e.size(); i++) {
if(s[i] != 0.0) {
gr[e[i][0]].push_back({e[i][1], s[i]});
gr[e[i][1]].push_back({e[i][0], s[i]});
merge(unionFind, e[i][0], e[i][1]);
}
}

if(getParent(unionFind, start) != getParent(unionFind, end)) return 0.0;

queue<int> q;
q.push(start);
dp[start] = 1.0;
while(!q.empty()) {
auto now = q.front();
q.pop();
for(auto& [nxt, prob]: gr[now]) {
double nxtScore = prob * dp[now];
if(!dp[nxt] || dp[nxt] < nxtScore) {
dp[nxt] = nxtScore;
q.push(nxt);
}
}

}

return dp[end];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/31/PS/LeetCode/path-with-maximum-probability/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.