Skip to content

Commit 7741235

Browse files
authored
Merge pull request #2375 from ys3593/main
Create 1514-path-with-maximum-probability.java
2 parents f32626a + b070260 commit 7741235

File tree

1 file changed

+74
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)