给你一个由 n 个节点(下标从 0 开始)组成的无向加权图,该图由一个描述边的列表组成,其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边,且该边遍历成功的概率为 succProb[i] 。
指定两个节点分别作为起点 start 和终点 end ,请你找出从起点到终点成功概率最大的路径,并返回其成功概率。
如果不存在从 start 到 end 的路径,请 返回 0 。只要答案与标准答案的误差不超过 1e-5 ,就会被视作正确答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-with-maximum-probability
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先把路径转化为带权值的邻接矩阵,使用bfs搜索,用一个double数组保存当前节点的最大值,若是当前路径大于当前节点值就如队,否侧就下一个搜索
class Solution {
public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
List<List<Node>> list=new ArrayList(n);
for(int i=0;i<n;i++)
{
list.add(new ArrayList());
}
for(int i=0;i<edges.length;i++)
{
int a=edges[i][0];
int b=edges[i][1];
double weigth=succProb[i];
list.get(a).add(new Node(b, weigth));
list.get(b).add(new Node(a, weigth));
}
double re=0;
Queue<Node> queue=new LinkedList();
double[]vi=new double[n];
queue.add(new Node(start, 1));
while(!queue.isEmpty())
{
Node node=queue.poll();
if(node.to==end)
{
re=Math.max(re, node.weight);
continue;
}
for(Node no:list.get(node.to))
{
double weight=no.weight*node.weight;
if(weight>vi[no.to])
{
vi[no.to]=weight;
queue.add(new Node(no.to,weight));
}
}
}
return vi[end];
}
class Node{
int to;//下一个节点
double weight;//当前权值
public Node(int to,double weight)
{
this.to=to;
this.weight=weight;
}
}
}