1514. Path with Maximum Probability (spfa, dijkstra)

BFS (spfa)

https://leetcode.com/problems/path-with-maximum-probability/discuss/731626/Java-Detailed-Explanation-BFS

T: O(e+nm), e is edges len, n is v nums, m is edge nums

S: O(e + n)

class Solution {
    class Pair {
        int node;
        double probability;
        Pair(int node, double probability) {
            this.node = node;
            this.probability = probability;
        }
    }
    public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
        Map<Integer, List<Pair>> map = new HashMap<>();
        for (int i = 0; i < edges.length; i++) { // build graph
            int[] edge = edges[i];
            map.putIfAbsent(edge[0], new ArrayList<>());
            map.putIfAbsent(edge[1], new ArrayList<>());
            
            map.get(edge[0]).add(new Pair(edge[1], succProb[i]));
            map.get(edge[1]).add(new Pair(edge[0], succProb[i]));
        }
        
        double[] probs = new double[n]; // used to record newest probas data
        probs[start] = 1; // init probs[start]
        
        Queue<Integer> queue = new ArrayDeque<>();
        queue.offer(start);
        
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            
            // fecth childs, notice to use getOrDefault
            for (Pair child : map.getOrDefault(cur, new ArrayList<>())) {
                int node = child.node;
                double probability = child.probability;
                
                // if node's probs >= new node's probs, no need to update data and add to queue
                if (probs[node] >= probs[cur]*probability) {
                    continue;
                }
                probs[node] = probs[cur]*probability;
                queue.offer(node);
            }
        }
        
        return probs[end]; // return end node's probs
    }
}

/*
solution1: BFS
因為 BFS 都是用在權重1的狀況下, 這題不是

權重1下, 會標記visited 來避免走過重複的

但因為這題不是權重 1, 所以有可能走重複的路徑會產生更好的結果(這裡是說到 end 的機率要最大

所以這提用 BFS 的話就需要重複走路徑, 直到新路徑並不會比較好時, 才不繼續
if (probs[node] >= probs[cur]*probability) {
    continue;
}

所以在最壞的狀況下, time complexity 可能會指數成長

但這題還是可以通過, 最優解是用 dijkstra

*/

spfa + priority queue

dijkstra, 保證最後結果是最優

演算法所需的時間為 O((|E|+|V|)\log |V|)}{\displaystyle O((|E|+|V|)\log |V|)}

https://leetcode.com/problems/path-with-maximum-probability/discuss/818701/Java-Dijkstra-template

Time: O((n + E) * logn), n is number of v

space: O(n + E), where E = edges.length.

return use Set

提前終止, 使用 Set 即可,

return use HashMap

如果不提前終止, 一律最後再回傳答案, use hashmap

latest version

T: O(ElogE), 把邊加入 PQ (Heap)

S: O(E + n) , map, pq 都用到 E, n -> set 用到(多少個點, 可以說是 v

注意, 還是得要維持一個目前的值 currentProb, 不然盲目的加入到 queue, 會很慢的

還是得比較是不是有更優

Last updated

Was this helpful?