Skip to content

Commit

Permalink
Create 1514. Path with Maximum Probability1 (#568)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Aug 27, 2024
2 parents 3a5ad48 + 2c7df38 commit 8517c0b
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions 1514. Path with Maximum Probability1
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public:
double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start_node, int end_node) {
vector<vector<pair<int, double>>> adj(n);
vector<double> dist(n, 0); // Initialize distance/probability array with 0
// Build the adjacency list
for (int i = 0; i < edges.size(); i++) {
int u = edges[i][0], v = edges[i][1];
adj[u].emplace_back(v, succProb[i]);
adj[v].emplace_back(u, succProb[i]);
}
priority_queue<pair<double, int>> pq;
pq.push({1, start_node}); // Start with probability 1 for the start node
dist[start_node] = 0; // Probability to reach start node is 1
while (!pq.empty()) {
auto [prob, node] = pq.top(); pq.pop();
if (node == end_node)
return prob;
for (auto& [neighbor, cost] : adj[node]) {
double newProb = prob * cost;
if (newProb > dist[neighbor]) {
dist[neighbor] = newProb;
pq.push({newProb, neighbor});
}
}
}
return 0;
}
};

0 comments on commit 8517c0b

Please sign in to comment.