@@ -439,6 +439,51 @@ impl Solution {
439
439
}
440
440
```
441
441
442
+ dfs: 版本二
443
+
444
+ ``` rust
445
+ impl Solution {
446
+ const DIRECTIONS : [(i32 , i32 ); 4 ] = [(0 , 1 ), (1 , 0 ), (- 1 , 0 ), (0 , - 1 )];
447
+
448
+ pub fn max_area_of_island (grid : Vec <Vec <i32 >>) -> i32 {
449
+ let mut visited = vec! [vec! [false ; grid [0 ]. len ()]; grid . len ()];
450
+
451
+ let mut res = 0 ;
452
+ for (i , nums ) in grid . iter (). enumerate () {
453
+ for (j , & num ) in nums . iter (). enumerate () {
454
+ if ! visited [i ][j ] && num == 1 {
455
+ let mut count = 0 ;
456
+ Self :: dfs (& grid , & mut visited , (i as i32 , j as i32 ), & mut count );
457
+ res = res . max (count );
458
+ }
459
+ }
460
+ }
461
+
462
+ res
463
+ }
464
+
465
+ pub fn dfs (
466
+ grid : & Vec <Vec <i32 >>,
467
+ visited : & mut [Vec <bool >],
468
+ (x , y ): (i32 , i32 ),
469
+ count : & mut i32 ,
470
+ ) {
471
+ if visited [x as usize ][y as usize ] || grid [x as usize ][y as usize ] == 0 {
472
+ return ;
473
+ }
474
+ visited [x as usize ][y as usize ] = true ;
475
+ * count += 1 ;
476
+ for (dx , dy ) in Self :: DIRECTIONS {
477
+ let (nx , ny ) = (x + dx , y + dy );
478
+ if nx < 0 || nx >= grid . len () as i32 || ny < 0 || ny >= grid [0 ]. len () as i32 {
479
+ continue ;
480
+ }
481
+ Self :: dfs (grid , visited , (nx , ny ), count );
482
+ }
483
+ }
484
+ }
485
+ ```
486
+
442
487
<p align="center">
443
488
<a href="https://programmercarl.com/other/kstar.html " target="_ blank">
444
489
<img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
0 commit comments