当前位置: 首页 > article >正文

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算法

代码实现:

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];
    }
}


http://www.kler.cn/news/284928.html

相关文章:

  • 栈算法【基于顺序表】
  • centos 系统yum 安装 mariadb
  • UML类图中的组合关系
  • Vue3 + Axios双Token刷新解决方案
  • MySQL——多表操作(四)子查询(1)带 IN 关键字的子查询
  • Xilinx高速接口之GTP
  • CSS 预处理器
  • 10、ollama启动LLama_Factory微调大模型(llama.cpp)
  • opencv之形态学
  • 喜羊羊做Python真题
  • 基于Android+SQLite数据库开发Java考试App
  • 深度学习100问15:什么是交叉熵误差
  • 【Linux】Linux Bash Shell 教程
  • 工程师们都爱看的Docker容器技术,一看就会!保姆级教程(上)
  • Nginx负载均衡请求队列配置:优化流量管理
  • MySQL:简述事务的SQL操作
  • K8S Job
  • CSS优化实践
  • 计算机毕业设计选题推荐-二手物品回收系统-Java/Python项目实战
  • Nuxt3入门:资源文件(第2节)
  • LeetCode第65题 有效数字 结合设计模式:状态模式
  • Linux下C++编程使用动态链接库
  • Openldap可视化工具PhpLdapAdmin服务配置
  • TMPDIR在pip|pip3 install时的作用以及tmp只有noexec权限的解决方法
  • 问题记录之Qt Creator下qDebug中文乱码
  • SparkSQL缓存的用法
  • IM社交-前言
  • 负载均衡的分类有哪些?
  • 路由策略工具
  • 51单片机——模块化编程