-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path24-frog-position-after-t-seconds.rs
50 lines (49 loc) · 1.51 KB
/
24-frog-position-after-t-seconds.rs
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
// https://leetcode.cn/problems/frog-position-after-t-seconds/
impl Solution {
pub fn frog_position(n: i32, edges: Vec<Vec<i32>>, t: i32, target: i32) -> f64 {
let mut g = vec![vec![]; n as usize + 1];
for edge in edges {
g[edge[0] as usize].push(edge[1] as usize);
g[edge[1] as usize].push(edge[0] as usize);
}
let mut vis = vec![false; n as usize + 1];
vis[1] = true;
fn dfs(
edges: &Vec<Vec<usize>>,
pos: usize,
probability: f64,
vis: &mut Vec<bool>,
t: i32,
target: i32,
) -> f64 {
if t == 0 {
if pos as i32 == target {
return probability;
} else {
return 0.0;
}
}
let cnt = edges[pos]
.iter()
.filter(|&x| !vis[*x])
.count();
if cnt == 0 {
if pos as i32 == target {
return probability;
} else {
return 0.0;
}
}
let mut ans = 0.0;
for &next in edges[pos].iter() {
if !vis[next] {
vis[next] = true;
ans += dfs(edges, next, probability / cnt as f64, vis, t - 1, target);
vis[next] = false;
}
}
ans
}
dfs(&g, 1, 1.0, &mut vis, t, target)
}
}