1514. Path with Maximum Probability
class Solution {
double[] succProb;
public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
this.succProb = succProb;
List<double[]>[] graph = toGraph(edges, n);
return dijkstra(graph, start, end);
}
private double dijkstra(List<double[]>[] graph, int start, int end){
double[] memo = new double[graph.length];
// int[0] is the node, int[1] is the possibility
PriorityQueue<double[]> queue = new PriorityQueue<>((a,b)-> b[1]-a[1] >0 ? 1 : -1);
queue.offer(new double[]{start, 1.0});
while(!queue.isEmpty()){
double[] curr =queue.poll();
if(curr[0]==end) return curr[1];
if(curr[1]<memo[(int) curr[0]]) continue;
for(double[] next: graph[(int) curr[0]]){
double nextProb = curr[1]*next[1];
if(nextProb>memo[(int) next[0]]){
queue.offer(new double[]{next[0], nextProb});
memo[(int) next[0]]=nextProb;
}
}
}
return 0;
}
private List<double[]>[] toGraph(int[][] edges, int n){
// int[0] is the node, int[1] is the possibility
List<double[]>[] graph = new LinkedList[n];
for(int i=0; i<n; i++){
graph[i]=new LinkedList<>();
}
for(int i=0; i<edges.length; i++){
int[] edge = edges[i];
graph[edge[0]].add(new double[]{edge[1], succProb[i]});
graph[edge[1]].add(new double[]{edge[0], succProb[i]});
}
return graph;
}
}
Last updated
Was this helpful?