1
1
pub struct Solution { }
2
2
3
3
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
+ }
5
30
}
6
31
7
32
#[ cfg( test) ]
8
33
mod tests {
9
34
use super :: * ;
10
35
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
+
11
54
#[ test]
12
55
fn example_1 ( ) {
13
56
let grid = [
@@ -20,11 +63,9 @@ mod tests {
20
63
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 0 , 0 ] ,
21
64
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 ] ,
22
65
] ;
66
+ let grid = grid. iter ( ) . map ( |row| row. to_vec ( ) ) . collect ( ) ;
23
67
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) ;
28
69
}
29
70
30
71
#[ test]
0 commit comments