5211. 概率最大的路徑(197)
阿新 • • 發佈:2020-07-12
class Solution { public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { Map<Integer,List<Node>> map = new HashMap<>(); for(int i = 0; i < edges.length; i++) { map.computeIfAbsent(edges[i][0],k->new ArrayList<>()).add(newNode(edges[i][1],succProb[i])); map.computeIfAbsent(edges[i][1],k->new ArrayList<>()).add(new Node(edges[i][0],succProb[i])); } Queue<Node> queue = new PriorityQueue<>((o1,o2)->Double.compare(o2.pro,o1.pro)); queue.add(new Node(start,1.0));boolean[] st = new boolean[n]; while(!queue.isEmpty()) { Node cur = queue.poll(); if(cur.node == end) return cur.pro; if(!st[cur.node]) { st[cur.node] = true; List<Node> list = map.get(cur.node); if(list == null) continue; for(Node nn : list) { queue.add(new Node(nn.node,nn.pro*cur.pro)); } } } return 0; } } class Node { int node; double pro; public Node (int n, double p) { node = n; pro = p; } }