You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
Example 2:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000Explanation: There is an edge which connects the nodes 0 and 2 with probability = 0.3.
Example 3:
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000Explanation: There is no path between 0 and 2.
Constraints:
2 <= n <= 10,0000 <= start, end < nstart != end0 <= a, b < na != b0 <= succProb.length == edges.length <= 20,0000 <= succProb[i] <= 1Before attempting this problem, you should be comfortable with:
This problem asks for the path with maximum probability, which is similar to finding the shortest path but with multiplication instead of addition. Since probabilities are between 0 and 1, multiplying them gives smaller values, so we want to maximize the product. Dijkstra's algorithm works here because we can negate probabilities (or use a max-heap) to always process the most promising path first. Once we reach the destination, we have found the optimal path.
1.0 at the source node.0.class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
adj = collections.defaultdict(list)
for i in range(len(edges)):
src, dst = edges[i]
adj[src].append((dst, succProb[i]))
adj[dst].append((src, succProb[i]))
pq = [(-1, start_node)]
visit = set()
while pq:
prob, cur = heapq.heappop(pq)
visit.add(cur)
if cur == end_node:
return -prob
for nei, edgeProb in adj[cur]:
if nei not in visit:
heapq.heappush(pq, (prob * edgeProb, nei))
return 0.0Where is the number nodes and is the number of edges.
This is a refined version of Dijkstra's algorithm that tracks the maximum probability to reach each node. Instead of just using a visited set, we maintain an array storing the best probability found so far for each node. This allows us to skip processing a node if we have already found a better path to it, reducing unnecessary work.
maxProb array where maxProb[i] stores the highest probability to reach node i. Set maxProb[start] = 1.0.(1.0, start_node).0 if the destination is unreachable.class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
adj = [[] for _ in range(n)]
for i in range(len(edges)):
src, dst = edges[i]
adj[src].append((dst, succProb[i]))
adj[dst].append((src, succProb[i]))
maxProb = [0] * n
maxProb[start_node] = 1.0
pq = [(-1.0, start_node)]
while pq:
curr_prob, node = heapq.heappop(pq)
curr_prob *= -1
if node == end_node:
return curr_prob
if curr_prob > maxProb[node]:
continue
for nei, edge_prob in adj[node]:
new_prob = curr_prob * edge_prob
if new_prob > maxProb[nei]:
maxProb[nei] = new_prob
heapq.heappush(pq, (-new_prob, nei))
return 0.0Where is the number nodes and is the number of edges.
The Bellman-Ford algorithm can find the best path by relaxing all edges repeatedly. For this problem, we relax edges to maximize probability instead of minimizing distance. Since the graph is undirected, we check both directions for each edge. The algorithm runs for at most n iterations, but we can stop early if no updates occur in a round, meaning we have found the optimal solution.
maxProb array with all zeros except maxProb[start] = 1.0.n iterations, iterate through all edges.(src, dst) with probability p, try to relax in both directions: if maxProb[src] * p > maxProb[dst], update maxProb[dst], and vice versa.maxProb[end_node].class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
maxProb = [0.0] * n
maxProb[start_node] = 1.0
for i in range(n):
updated = False
for j in range(len(edges)):
src, dst = edges[j]
if maxProb[src] * succProb[j] > maxProb[dst]:
maxProb[dst] = maxProb[src] * succProb[j]
updated = True
if maxProb[dst] * succProb[j] > maxProb[src]:
maxProb[src] = maxProb[dst] * succProb[j]
updated = True
if not updated:
break
return maxProb[end_node]Where is the number nodes and is the number of edges.
SPFA is an optimization of Bellman-Ford that uses a queue to process only nodes whose distances (or probabilities) have changed. Instead of iterating through all edges in every round, we only process edges from nodes that might lead to improvements. This can be significantly faster in practice, especially for sparse graphs.
maxProb array with maxProb[start] = 1.0.maxProb[end_node].class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
adj = [[] for _ in range(n)]
for i in range(len(edges)):
src, dst = edges[i]
adj[src].append((dst, succProb[i]))
adj[dst].append((src, succProb[i]))
maxProb = [0.0] * n
maxProb[start_node] = 1.0
q = deque([start_node])
while q:
node = q.popleft()
for nei, edge_prob in adj[node]:
new_prob = maxProb[node] * edge_prob
if new_prob > maxProb[nei]:
maxProb[nei] = new_prob
q.append(nei)
return maxProb[end_node]Where is the number nodes and is the number of edges.
Unlike shortest path problems where we minimize distance, this problem requires maximizing probability. Using a min-heap (the default in most languages) will process low-probability paths first, leading to incorrect results or inefficiency. Always use a max-heap or negate the probabilities when using a min-heap.
The starting node should have a probability of 1.0 (certainty), not 0.0. Multiplying any edge probability by zero will always yield zero, preventing the algorithm from finding any valid path. Initialize maxProb[start_node] = 1.0 before beginning the search.
Each edge connects two nodes bidirectionally, so you must add both directions to the adjacency list. Forgetting to add the reverse edge means some paths will be unreachable, potentially missing the optimal solution or returning zero when a valid path exists.