-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0695-max-area-of-island.rs
38 lines (31 loc) · 1.01 KB
/
0695-max-area-of-island.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
impl Solution {
pub fn max_area_of_island(grid: Vec<Vec<i32>>) -> i32 {
fn dfs(grid: &mut Vec<Vec<i32>>, x: i32, y: i32) -> i32 {
if x < 0
|| y < 0
|| x >= grid.len() as i32
|| y >= grid[0].len() as i32
|| grid[x as usize][y as usize] == 0
{
return 0;
}
grid[x as usize][y as usize] = 0;
let mut count = 1;
let directions: [(i32, i32); 4] = [(0, 1), (1, 0), (0, -1), (-1, 0)];
for (add_x, add_y) in directions {
count += dfs(grid, x + add_x, y + add_y);
}
count
}
let mut max_area = 0;
let mut new_grid = grid.clone();
for x in 0..grid.len() {
for y in 0..grid[0].len() {
if new_grid[x][y] == 1 {
max_area = max_area.max(dfs(&mut new_grid, x as i32, y as i32));
}
}
}
max_area
}
}