Path with Maximum Probability

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 endreturn 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

Example 1:

 

Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.

思路:就是dijkstra算法,每次走path pos最大的node,就跟 Connecting Cities With Minimum Cost 一模一样的思路。city里面存pos,这样每次poll出来就是最大的pos的path,如果遇见了end,就是最大值;

class Solution {
    private class Node {
        public int city;
        public double pos;
        public Node(int city, double pos) {
            this.city = city;
            this.pos = pos;
        }
    }
    
    public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
        HashMap<Integer, List<Node>> graph = new HashMap<>();
        for(int i = 0; i < n; i++) {
            graph.putIfAbsent(i, new ArrayList<Node>());
        }
        
        for(int i = 0; i < edges.length; i++) {
            int a = edges[i][0];
            int b = edges[i][1];
            graph.get(a).add(new Node(b, succProb[i]));
            graph.get(b).add(new Node(a, succProb[i]));
        }
        
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (int)((b.pos - a.pos) * 1000));
        pq.offer(new Node(start, 1.0));
        HashSet<Integer> visited = new HashSet<>();
        
        while(!pq.isEmpty()) {
            Node node = pq.poll();
            if(visited.contains(node.city)) {
                continue;
            }
            if(node.city == end) {
                return node.pos;
            }
            visited.add(node.city);
            for(Node neighbor: graph.get(node.city)) {
                if(!visited.contains(neighbor.city)) {
                    pq.offer(new Node(neighbor.city, node.pos * neighbor.pos));
                }
            }
        }
        return 0;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值