-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1514. Path with Maximum Probability1 (#568)
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |