1514. 概率最大的路径

Medium

思路

看了数据规模估计Floyd算法会超时,果然TLE

尝试使用Dijkstra同源最短路径算法,有关Dijkstra算法的具体教程,可以查看743. 网络延迟时间的解题

遇到的问题

以上,有点费劲的AC!

代码

python3

class Solution:
    def closestNode(self,visited,queue):
      probs, node = heapq.heappop(queue)
      while visited[node] and len(queue) > 0:
        probs, node = heapq.heappop(queue)
      return probs, node

    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
      graph = {}
      for i, item in enumerate(edges):
          s, e, p = item[0], item[1], succProb[i]
          graph.setdefault(s, []).append((e, p))
          graph.setdefault(e, []).append((s, p)) 
      visited = [False for _ in range(n)]
      cur_node = start
      queue = []
      heapq.heappush(queue, (-1, start))
      for _ in range(n):
        if len(queue) == 0:
          return 0
        cur_probs, cur_node = self.closestNode(visited,queue)
        if cur_node not in graph:
          return 0
        visited[cur_node] = True
        if cur_node == end:
          return -cur_probs
        for i in graph[cur_node]:
          if not visited[i[0]]:
            heapq.heappush(queue, (i[1] * cur_probs , i[0]))
      return 0