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];
    }
}
相关推荐
Moonbit8 分钟前
MGPIC 初赛提交倒计时 4 天!
后端·算法·编程语言
Miraitowa_cheems25 分钟前
LeetCode算法日记 - Day 98: 分割回文串 II
数据结构·算法·leetcode·深度优先·动态规划
立志成为大牛的小牛31 分钟前
数据结构——三十九、顺序查找(王道408)
数据结构·学习·程序人生·考研·算法
2301_8079973836 分钟前
代码随想录-day30
数据结构·c++·算法·leetcode
爱代码的小黄人1 小时前
一般角度的旋转矩阵的推导
线性代数·算法·矩阵
ゞ 正在缓冲99%…1 小时前
leetcode1771.由子序列构造的最长回文串长度
数据结构·算法·leetcode
多喝开水少熬夜1 小时前
堆相关算法题基础-java实现
java·开发语言·算法
锂享生活2 小时前
论文阅读:铁路车辆跨临界 CO₂ 空调系统模型预测控制(MPC)策略
论文阅读·算法
B站_计算机毕业设计之家2 小时前
深度学习:Yolo水果检测识别系统 深度学习算法 pyqt界面 训练集测试集 深度学习 数据库 大数据 (建议收藏)✅
数据库·人工智能·python·深度学习·算法·yolo·pyqt
骑自行车的码农2 小时前
React SSR 技术实现原理
算法·react.js