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.25000
Explanation: 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.
思路:就是dijkstra算法,每次走path pos最大的node,就跟 Connecting Cities With Minimum Cost 一模一样的思路。city里面存pos,这样每次poll出来就是最大的pos的path,如果遇见了end,就是最大值;
class Solution {
private class Node {
public int city;
public double pos;
public Node(int city, double pos) {
this.city = city;
this.pos = pos;
}
}
public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
HashMap<Integer, List<Node>> graph = new HashMap<>();
for(int i = 0; i < n; i++) {
graph.putIfAbsent(i, new ArrayList<Node>());
}
for(int i = 0; i < edges.length; i++) {
int a = edges[i][0];
int b = edges[i][1];
graph.get(a).add(new Node(b, succProb[i]));
graph.get(b).add(new Node(a, succProb[i]));
}
PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (int)((b.pos - a.pos) * 1000));
pq.offer(new Node(start, 1.0));
HashSet<Integer> visited = new HashSet<>();
while(!pq.isEmpty()) {
Node node = pq.poll();
if(visited.contains(node.city)) {
continue;
}
if(node.city == end) {
return node.pos;
}
visited.add(node.city);
for(Node neighbor: graph.get(node.city)) {
if(!visited.contains(neighbor.city)) {
pq.offer(new Node(neighbor.city, node.pos * neighbor.pos));
}
}
}
return 0;
}
}