leetcode1514 最大概率路径(Bellman-ford算法详解)

题目描述:

You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edgesi = a, b is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProbi.

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.
题目链接

解题思路:

为了解决这个问题,我们需要在无向图中找到两个节点之间的路径,以最大化边概率的乘积。Bellman-Ford算法通常用于在具有负权重的图中找到最短路径,可以用来解决这个问题。我们将通过迭代更新起始点到达每个节点的最大概率来求最终的最大概率。
Bellman-Ford算法

代码实现:

java 复制代码
package practise;

public class leetcode1514 {
    public static void main(String[] args) {
        int[][] edges = {{2,3},{1,2},{3,4},{1,3},{1,4},{0,1},{2,4},{0,4},{0,2}};
        double[] succProb = {0.06,0.26,0.49,0.25,0.2,0.64,0.23,0.21,0.77};
        System.out.println(maxProbability(5, edges, succProb, 0, 3));
    }

    public static double maxProbability(int n, int[][] edges, double[] succProb, int start_node, int end_node) {
        double[] maxProb = new double[n]; //the pro from start_node to xxx
        maxProb[start_node] = 1.0;
        for (int i = 0; i < edges.length; i++) {
            boolean updated = false;
            for (int j = 0; j < edges.length; j++) {
                int from = edges[j][0], to = edges[j][1];
                double pathProb = succProb[j];
                if (maxProb[from] * pathProb > maxProb[to]) {
                    maxProb[to] = maxProb[from] * pathProb;
                    updated = true;
                }
                if (maxProb[to] * pathProb > maxProb[from]) {
                    maxProb[from] = maxProb[to] * pathProb;
                    updated = true;
                }
            }
            if(!updated) {
                break;
            }
        }
        return maxProb[end_node];
    }
}
相关推荐
hanlin0342 分钟前
刷题笔记:力扣第84题-柱状图中最大的矩形
笔记·算法·leetcode
青少儿编程课堂1 小时前
威佐夫博弈(双堆取子游戏)解析
c++·python·算法·bfs·信息学竞赛
辰烨chenye6 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
hqyjzsb9 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye9 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
微功夫信息技术9 小时前
分层多智能体强化学习驱动的非急救转运公平 - 效率统一调度系统研究与实践
人工智能·学习·算法·动态规划
sanjiaomao33310 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试
乐迪信息10 小时前
如何通过AI防爆摄像机精准判断船舶超速?
大数据·人工智能·算法·安全·目标跟踪
大圣编蚕11 小时前
Java ByteArrayInputStream 详解:从入门到实战
java·开发语言·算法
小玮看世界12 小时前
[Python]OD算法在OD实际运用转化参考清单
开发语言·python·算法