-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1514-path-with-maximum-probability.java
74 lines (63 loc) · 2.18 KB
/
1514-path-with-maximum-probability.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution {
public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
// create the graph
List<double[]>[] graph = new LinkedList[n];
for (int i = 0; i < n; i++) {
graph[i] = new LinkedList<>();
}
for (int i = 0; i < edges.length; i++) {
double from = edges[i][0];
double to = edges[i][1];
double weight = succProb[i];
double[] m = new double[2];
m[0] = to;
m[1] = weight;
graph[edges[i][0]].add(m);
double[] k = new double[2];
k[0] = from;
k[1] = weight;
graph[edges[i][1]].add(k);
}
// call dijkstra and return
return dijkstra(start, end, graph);
}
class State{
int id;
double proToStart;
public State(int id, double proToStart){
this.id = id;
this.proToStart = proToStart;
}
}
private double dijkstra(int start, int end, List<double[]>[] graph){
double[] proTo = new double[graph.length];
// 初始化为一个去不到的值
Arrays.fill(proTo, -1);
proTo[start] = 1;
PriorityQueue<State> pq = new PriorityQueue<State>((a, b) -> {
return Double.compare(b.proToStart, a.proToStart);
});
pq.offer(new State(start, 1));
while (!pq.isEmpty()){
State cur = pq.poll();
int curid = cur.id;
double curproToStart = cur.proToStart;
if (curid == end) {
return curproToStart;
}
if (proTo[curid] > curproToStart) {
continue;
}
List<double[]> nexts = graph[curid];
for (double[] next: nexts) {
double proToNext = proTo[curid] * next[1];
int idx = (int) next[0];
if (proToNext > proTo[idx]) {
proTo[idx] = proToNext;
pq.offer(new State(idx, proToNext));
}
}
}
return 0;
}
}