1514. Path with Maximum Probability #415
-
Topics: You are given an undirected weighted graph of Given two nodes If there is no path from Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a modified version of Dijkstra's algorithm. Instead of finding the shortest path, you'll be maximizing the probability of success. Let's implement this solution in PHP: 1514. Path with Maximum Probability <?php
function maxProbability($n, $edges, $succProb, $start_node, $end_node) {
// Create an adjacency list to represent the graph
$graph = array_fill(0, $n, []);
foreach ($edges as $i => $edge) {
list($a, $b) = $edge;
$graph[$a][] = [$b, $succProb[$i]];
$graph[$b][] = [$a, $succProb[$i]];
}
// Initialize the maximum probabilities array
$maxProb = array_fill(0, $n, 0.0);
$maxProb[$start_node] = 1.0;
// Use a max heap (priority queue) to explore the paths
$pq = new SplPriorityQueue();
$pq->insert([$start_node, 1.0], 1.0);
// Dijkstra's algorithm to find the path with maximum probability
while (!$pq->isEmpty()) {
list($node, $prob) = $pq->extract();
// If we reached the end node, return the probability
if ($node == $end_node) {
return $prob;
}
// Explore the neighbors
foreach ($graph[$node] as $neighbor) {
list($nextNode, $edgeProb) = $neighbor;
$newProb = $prob * $edgeProb;
if ($newProb > $maxProb[$nextNode]) {
$maxProb[$nextNode] = $newProb;
$pq->insert([$nextNode, $newProb], $newProb);
}
}
}
// If no path was found, return 0
return 0.0;
}
// Example usage:
$n1 = 3;
$edges1 = [[0,1],[1,2],[0,2]];
$succProb1 = [0.5,0.5,0.2];
$start_node1 = 0;
$end_node1 = 2;
echo maxProbability($n1, $edges1, $succProb1, $start_node1, $end_node1);//Output: 0.25000
$n2 = 3;
$edges2 = [[0,1],[1,2],[0,2]];
$succProb2 = [0.5,0.5,0.3];
$start_node2 = 0;
$end_node2 = 2;
echo maxProbability($n2, $edges2, $succProb2, $start_node2, $end_node2);//Output: 0.30000
$n3 = 3;
$edges3 = [[0,1]];
$succProb3 = [0.5;
$start_node3 = 0;
$end_node3 = 2;
echo maxProbability($n3, $edges3, $succProb3, $start_node3, $end_node3); //Output: 0.00000
?> Explanation:
Output:For the example provided: $n = 3;
$edges = [[0,1],[1,2],[0,2]];
$succProb = [0.5,0.5,0.2];
$start_node = 0;
$end_node = 2; The output will be This approach ensures an efficient solution using Dijkstra's algorithm while handling the specifics of probability calculations. |
Beta Was this translation helpful? Give feedback.
We can use a modified version of Dijkstra's algorithm. Instead of finding the shortest path, you'll be maximizing the probability of success.
Let's implement this solution in PHP: 1514. Path with Maximum Probability