-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path22-pond-sizes-lcci.rs
43 lines (43 loc) · 1.31 KB
/
22-pond-sizes-lcci.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
impl Solution {
pub fn pond_sizes(land: Vec<Vec<i32>>) -> Vec<i32> {
let mut ans = vec![];
let mut vis = vec![vec![false; land[0].len()]; land.len()];
fn dfs(land: &Vec<Vec<i32>>, vis: &mut Vec<Vec<bool>>, x: usize, y: usize) -> i32 {
let mut ans = 1;
vis[x][y] = true;
for &(dx, dy) in [
(0, 1),
(0, -1),
(1, 0),
(-1, 0),
(-1, -1),
(-1, 1),
(1, -1),
(1, 1),
]
.iter()
{
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
if nx >= 0
&& nx < land.len() as i32
&& ny >= 0
&& ny < land[0].len() as i32
&& land[nx as usize][ny as usize] == 0
&& !vis[nx as usize][ny as usize]
{
ans += dfs(land, vis, nx as usize, ny as usize);
}
}
ans
}
for i in 0..land.len() {
for j in 0..land[0].len() {
if land[i][j] == 0 && !vis[i][j] {
ans.push(dfs(&land, &mut vis, i, j));
}
}
}
ans.sort_unstable();
ans
}
}