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];
    }
}
相关推荐
wfbcg26 分钟前
每日算法练习:LeetCode 167. 两数之和 II - 输入有序数组 ✅
算法·leetcode·职场和发展
A~MasterYi41 分钟前
深入理解 Microscaling (MX) 格式:从浮点基础到共享指数矩阵乘法
算法·矩阵
环黄金线HHJX.1 小时前
《Tuan(拼音字母)⇆团(Group)/&湍(Turbulence)/&双结构链路道/&文字、符号、语言/&源点设计、连接起:人类与自然+AICosmOS》
开发语言·人工智能·算法·编辑器
有时间要学习1 小时前
面试150——第七周
算法·面试·深度优先
AI科技星1 小时前
万能学习方法论的理论建构与多领域适配性研究(乖乖数学)
人工智能·学习·算法·机器学习·平面·数据挖掘
Ashore11_2 小时前
蓝桥杯16届Java研究生组
java·算法·蓝桥杯
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 76. 最小覆盖子串 | C++ 滑动窗口题解
c++·算法·leetcode
像素猎人2 小时前
蓝桥杯OJ2049蓝桥勇士【动态规划】【dp[n]不是符合题意的答案,只是以an结尾的子问题的答案】
c++·算法·蓝桥杯·动态规划·区间dp
羊小猪~~2 小时前
LLM--SFT简介
python·考研·算法·ai·大模型·llm·微调
广州灵眸科技有限公司2 小时前
瑞芯微(EASY EAI)RV1126B 人脸98关键点算法识别
开发语言·科技·嵌入式硬件·物联网·算法·php