forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFrog Position After T Seconds.java
49 lines (33 loc) · 1.21 KB
/
Frog Position After T Seconds.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
class Solution {
public double frogPosition(int n, int[][] edges, int t, int target) {
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++) graph.add(new ArrayList<>());
for(int i=0;i<edges.length;i++) {
graph.get(edges[i][0]).add(edges[i][1]);
graph.get(edges[i][1]).add(edges[i][0]);
}
boolean[] vis=new boolean[n+1];
return Sol(graph,1, t, target,vis);
}
public double Sol(List<List<Integer>> graph,int ver,int t,int tar,boolean[] vis){
int count=0;
for(Integer child:graph.get(ver)){
if(!vis[child]) count++;
}
vis[ver]=true;
if(t<0) return 0;
if(ver==tar){
if(count==0 || t==0) return 1.0;
}
if(graph.get(ver).size()==0) return 0;
double ans=0.0;
for(Integer child:graph.get(ver)){
// System.out.println(child);
if(!vis[child])
ans+=(double)(1.0/count)*Sol(graph,child,t-1,tar,vis);
}
// System.out.println(ans);
vis[ver]=false;
return ans;
}
}