Skip to content

Commit 8517c0b

Browse files
authored
Create 1514. Path with Maximum Probability1 (#568)
2 parents 3a5ad48 + 2c7df38 commit 8517c0b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

1514. Path with Maximum Probability1

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start_node, int end_node) {
4+
vector<vector<pair<int, double>>> adj(n);
5+
vector<double> dist(n, 0); // Initialize distance/probability array with 0
6+
// Build the adjacency list
7+
for (int i = 0; i < edges.size(); i++) {
8+
int u = edges[i][0], v = edges[i][1];
9+
adj[u].emplace_back(v, succProb[i]);
10+
adj[v].emplace_back(u, succProb[i]);
11+
}
12+
priority_queue<pair<double, int>> pq;
13+
pq.push({1, start_node}); // Start with probability 1 for the start node
14+
dist[start_node] = 0; // Probability to reach start node is 1
15+
while (!pq.empty()) {
16+
auto [prob, node] = pq.top(); pq.pop();
17+
if (node == end_node)
18+
return prob;
19+
for (auto& [neighbor, cost] : adj[node]) {
20+
double newProb = prob * cost;
21+
if (newProb > dist[neighbor]) {
22+
dist[neighbor] = newProb;
23+
pq.push({newProb, neighbor});
24+
}
25+
}
26+
}
27+
return 0;
28+
}
29+
};

0 commit comments

Comments
 (0)