- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1377.java
52 lines (50 loc) · 1.92 KB
/
_1377.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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Queue;
publicclass_1377 {
publicstaticclassSolution1 {
/*
* credit: https://leetcode.com/problems/frog-position-after-t-seconds/discuss/532505/Java-Straightforward-BFS-Clean-code-O(N)
*/
publicdoublefrogPosition(intn, int[][] edges, intt, inttarget) {
List<Integer>[] graph = newArrayList[n];
for (inti = 0; i < n; i++) {
graph[i] = newArrayList<>();
}
for (int[] edge : edges) {
graph[edge[0] - 1].add(edge[1] - 1);
graph[edge[1] - 1].add(edge[0] - 1);
}
boolean[] visited = newboolean[n];
visited[0] = true;
double[] probabilities = newdouble[n];
probabilities[0] = 1f;
Queue<Integer> queue = newLinkedList<>();
queue.offer(0);
while (!queue.isEmpty() && t-- > 0) {
for (inti = queue.size(); i > 0; i--) {
intvertex = queue.poll();
intnextVerticesCount = 0;
for (intnext : graph[vertex]) {
if (!visited[next]) {
nextVerticesCount++;
}
}
for (intnext : graph[vertex]) {
if (!visited[next]) {
visited[next] = true;
queue.offer(next);
probabilities[next] = probabilities[vertex] / nextVerticesCount;
}
}
if (nextVerticesCount > 0) {
probabilities[vertex] = 0;
}
}
}
returnprobabilities[target - 1];
}
}
}