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

题目描述:

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

解题思路:

为了解决这个问题,我们需要在无向图中找到两个节点之间的路径,以最大化边概率的乘积。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];
    }
}
相关推荐
wayz115 分钟前
Day 11 编程实战:XGBoost金融预测与调参
算法·机器学习·金融·集成学习·boosting
念越7 分钟前
算法每日一题 Day07|双指针求解和为S的两个数
算法·力扣
qeen8714 分钟前
【算法笔记】双指针及其经典例题解析
c++·笔记·算法·双指针
黎阳之光16 分钟前
黎阳之光:以视频孪生+全域感知,助力低空经济破局突围
大数据·人工智能·算法·安全·数字孪生
CM莫问1 小时前
详解机器学习中的马尔可夫链
人工智能·算法·机器学习·概率论·马尔可夫·马尔科夫
南宫萧幕1 小时前
基于 Luenberger 观测器的 PMSM 无速度传感器 id=0 矢量控制系统 Simulink 建模与实现(一)
算法·matlab·汽车·控制
斯维赤1 小时前
每天学习一个小算法:选择排序
java·学习·算法
超级码力6661 小时前
【Latex第三方文档类standalone】standalone类介绍及应用
算法·数学建模·信息可视化
明朝百晓生1 小时前
强化学习 [chapter10] [page3 ]Actor-Critic Methods
算法
peterfei1 小时前
一个 Tauri + Rust AI 编辑器是怎么同时适配 5 家 AI 大厂的?IfAI v0.4.3 架构拆解
人工智能·算法·架构