Leetcode 每日一题练习 ------ 1514. 概率最大的路径

Leetcode 每日一题练习继续讨论:

1514. 概率最大的路径
1514. Path with Maximum Probability

题解

本题寻找从一个点到另外一个点的最大可能性, 其实与寻找从一个点到另外一个点的最小距离异曲同工, 而这个图是一个无向图且边的权重均为正, 这能让我们想到dijistra算法. 只是需要对dijistra算法进行一些改动, 将计算两点之间的最短距离改为计算两点之间路径的总的可能性, 将每次从队列中取出距离原点距离最近的点改为取出距离原点可能性最大的点, 其余部分不变.

实现dijistra算法在寻找当前队列中到原点距离最短的节点时,如果使用数组则需遍历整个数组, 但使用优先级队列则可以直接得到有最短距离的节点(本题中为最大可能性)

代码

type Edge struct {
  to         int
  probability float64
}

type Graph [][]Edge

func buildGraph(n int, edges [][]int, succProb []float64) Graph {
  graph := make(Graph, n)
  for i, edge := range edges {
    from, to := edge[0], edge[1]
    prob := succProb[i]
    graph[from] = append(graph[from], Edge{to: to, probability: prob})
    graph[to] = append(graph[to], Edge{to: from, probability: prob})
  }
  return graph
}

type Item struct {
  node       int
  probability float64
  index      int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool { return pq[i].probability > pq[j].probability }
func (pq PriorityQueue) Swap(i, j int) {
  pq[i], pq[j] = pq[j], pq[i]
  pq[i].index = i
  pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
  n := len(*pq)
  item := x.(*Item)
  item.index = n
  *pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
  old := *pq
  n := len(old)
  item := old[n-1]
  old[n-1] = nil
  item.index = -1
  *pq = old[0 : n-1]
  return item
}

func maxProbability(n int, edges [][]int, succProb []float64, start_node int, end_node int) float64 {
  graph := buildGraph(n, edges, succProb)
  
  probs := make([]float64, n)
  probs[start_node] = 1.0

  pq := make(PriorityQueue, 0)
  heap.Init(&pq)
  heap.Push(&pq, &Item{node: start_node, probability: 1.0})

  for pq.Len() > 0 {
    item := heap.Pop(&pq).(*Item)
    node := item.node
    prob := item.probability

    if node == end_node {
      return prob
    }

    if prob < probs[node] {
      continue
    }

    for _, edge := range graph[node] {
      newProb := prob * edge.probability
      if newProb > probs[edge.to] {
        probs[edge.to] = newProb
        heap.Push(&pq, &Item{node: edge.to, probability: newProb})
      }
    }
  }

  return 0.0
}
3 个赞

刷题佬!先mark~

1 个赞

哇,刷题佬!

1 个赞

From 算法 to 开发调优