Skip to content

Commit 96836b7

Browse files
authored
Merge pull request chipbk10#86 from chipbk10/Graph
Solve Problem 1377 - Frog Position After T Seconds
2 parents 526a57e + bb282e5 commit 96836b7

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

src/contest/ReadMe.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ public class ReadMe {
44

55
// TOPICS [v] [v] [x]
66

7-
// tree: 1339[v] 1325[v] 1379
8-
// graph: 997[v] 1361[v] 1043
9-
// dfs: 1319[v] 1254[v] 1377
7+
// tree: 1339[v] 1325[v] 1379[v]
8+
// graph: 997[v] 1361[v] 1043[v]
9+
// dfs: 1319[v] 1254[v] 1377[v]
1010
// bfs: 1345[v] 1368[!] 1311
1111
// backtrack: 1307[!] 1239[v] 1219
1212
// dp: 1349[!] 1340[v] 1367
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package graph.dfs;
2+
3+
import java.util.LinkedList;
4+
import java.util.List;
5+
6+
public class Problem1377_FrogPositionAfterTSeconds {
7+
8+
List<Integer>[] graph;
9+
10+
public double frogPosition(int n, int[][] edges, int t, int target) {
11+
graph = new LinkedList[n+1];
12+
for (int i = 1; i <= n; i++) graph[i] = new LinkedList<>();
13+
for (int[] e : edges) {
14+
int i = e[0], j = e[1];
15+
graph[i].add(j);
16+
graph[j].add(i);
17+
}
18+
19+
// edge cases
20+
if (graph[1].size() == 0) return (target == 1) ? 1 : 0;
21+
if (target == 1) return (graph[1].size() > 0) ? 0 : 1;
22+
23+
return dfs(0, 1, t, target);
24+
}
25+
26+
private double dfs(int parent, int node, int t, int target) {
27+
28+
// run out of time
29+
if (t == 0) return (node == target) ? 1 : 0;
30+
31+
// reach the target
32+
if (node == target) return (graph[node].size() == 1) ? 1 : 0;
33+
34+
for (int next : graph[node]) {
35+
if (next == parent) continue;
36+
double p = dfs(node, next, t-1, target);
37+
if (p != 0) {
38+
int childNodes = graph[node].size();
39+
if (node != 1) childNodes--;
40+
return p/childNodes;
41+
}
42+
}
43+
return 0;
44+
}
45+
}

0 commit comments

Comments
 (0)