Skip to content

Commit b060e5c

Browse files
committed
Create 1514-path-with-maximum-probability.cpp
1 parent dd1c582 commit b060e5c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start_node, int end_node) {
4+
// adj list mapping {node -> [(probability, neighborNode), ...]}
5+
unordered_map<int, vector<pair<double, int>>> adj;
6+
for (int i=0; i<edges.size(); ++i) {
7+
vector<int> edge = edges[i];
8+
adj[edge[0]].push_back({succProb[i], edge[1]});
9+
adj[edge[1]].push_back({succProb[i], edge[0]});
10+
}
11+
12+
// maxHeap storing pairs of (probability, node)
13+
priority_queue<pair<double, int>> pq;
14+
pq.push({1.0, start_node});
15+
16+
unordered_set<int> visited;
17+
18+
// applying Dijkstra's algorithm
19+
while (!pq.empty()) {
20+
double currProb = pq.top().first;
21+
int currNode = pq.top().second;
22+
pq.pop();
23+
24+
if (currNode == end_node)
25+
return currProb;
26+
27+
visited.insert(currNode);
28+
29+
for (auto& [nextProb, nextNode] : adj[currNode]) {
30+
if (visited.find(nextNode) == visited.end()) {
31+
pq.push({currProb*nextProb, nextNode});
32+
}
33+
}
34+
}
35+
36+
return 0.0;
37+
}
38+
};

0 commit comments

Comments
 (0)