Created
October 14, 2020 19:47
-
-
Save adamgarcia4/59054922454af17f633a7764043ed90d to your computer and use it in GitHub Desktop.
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
from collections import defaultdict | |
import heapq | |
class Solution: | |
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: | |
''' | |
Input | |
n - number of nodes | |
edges - (u,v) for an undirected edge. | |
succProb - edge[i]'s weight | |
start - start node | |
end - end node | |
Output | |
MAXIMUM probability for a given path | |
Constraint | |
Taking multiple edges MULTIPLIES their weights | |
Approach | |
Dijkstra's algorithm to find Optimal path | |
Optimal: | |
Highest probability. | |
Or use successProb directly and find MAXIMUM path | |
''' | |
adjList = defaultdict(list) | |
for idx, (u, v) in enumerate(edges): | |
weight = succProb[idx] | |
adjList[u].append((v, weight)) | |
adjList[v].append((u, weight)) | |
q = [] | |
heapq.heappush(q, (-1, start)) | |
visited = [False] * n | |
while q: | |
cumCost, node = heapq.heappop(q) | |
cumCost = -1 * cumCost | |
if visited[node]: | |
continue | |
visited[node] = True | |
# Early return works because this is a greedy approach | |
if node == end: | |
return cumCost | |
# BFS | |
for to, weight in adjList[node]: | |
heapq.heappush(q, (-1 * cumCost * weight, to)) | |
return 0.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment