Skip to content

Commit 12649f9

Browse files
committed
feat: resovled
1 parent cdcc99f commit 12649f9

File tree

1 file changed

+46
-5
lines changed

1 file changed

+46
-5
lines changed

max_area_of_island/src/lib.rs

+46-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,56 @@
11
pub struct Solution {}
22

33
impl Solution {
4-
pub fn max_area_of_island(grid: Vec<Vec<i32>>) -> i32 {}
4+
pub fn max_area_of_island(grid: Vec<Vec<i32>>) -> i32 {
5+
let mut grid = grid;
6+
let mut max = 0;
7+
for i in 0..grid.len() {
8+
for j in 0..grid[0].len() {
9+
max = max.max(Self::cal_area(&mut grid, i as i32, j as i32));
10+
}
11+
}
12+
max
13+
}
14+
15+
fn cal_area(grid: &mut Vec<Vec<i32>>, i: i32, j: i32) -> i32 {
16+
let mut area = 0;
17+
if grid[i as usize][j as usize] == 0 {
18+
return area;
19+
}
20+
grid[i as usize][j as usize] = 0;
21+
area += 1;
22+
for (r, c) in vec![(i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)] {
23+
if r < 0 || r == grid.len() as i32 || c < 0 || c == grid[0].len() as i32 {
24+
continue;
25+
}
26+
area += Self::cal_area(grid, r, c);
27+
}
28+
area
29+
}
530
}
631

732
#[cfg(test)]
833
mod tests {
934
use super::*;
1035

36+
#[test]
37+
fn test_cal_area() {
38+
let grid = [
39+
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
40+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
41+
[0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
42+
[0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
43+
[0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
44+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
45+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
46+
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
47+
];
48+
let mut grid = grid.iter().map(|row| row.to_vec()).collect();
49+
assert_eq!(Solution::cal_area(&mut grid, 0, 2), 1);
50+
assert_eq!(Solution::cal_area(&mut grid, 0, 7), 4);
51+
assert_eq!(Solution::cal_area(&mut grid, 1, 7), 0);
52+
}
53+
1154
#[test]
1255
fn example_1() {
1356
let grid = [
@@ -20,11 +63,9 @@ mod tests {
2063
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
2164
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
2265
];
66+
let grid = grid.iter().map(|row| row.to_vec()).collect();
2367
let expected = 6;
24-
assert_eq!(
25-
Solution::max_area_of_island(grid.iter().map(|row| row.to_vec()).collect()),
26-
expected
27-
);
68+
assert_eq!(Solution::max_area_of_island(grid), expected);
2869
}
2970

3071
#[test]

0 commit comments

Comments
 (0)