From 2c7df38aa7251fc8364ce73387a2a941187844dc Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Tue, 27 Aug 2024 17:32:36 +0530 Subject: [PATCH] Create 1514. Path with Maximum Probability1 --- 1514. Path with Maximum Probability1 | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1514. Path with Maximum Probability1 diff --git a/1514. Path with Maximum Probability1 b/1514. Path with Maximum Probability1 new file mode 100644 index 0000000..bccaa0b --- /dev/null +++ b/1514. Path with Maximum Probability1 @@ -0,0 +1,29 @@ +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start_node, int end_node) { + vector>> adj(n); + vector 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> 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; + } +};