Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c7ec1d7

Browse files
authored
Update 0695.岛屿的最大面积.md
1 parent d02c6a7 commit c7ec1d7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎problems/0695.岛屿的最大面积.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,53 @@ impl Solution {
484484
}
485485
```
486486

487+
bfs:
488+
489+
```rust
490+
use std::collections::VecDeque;
491+
impl Solution {
492+
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];
493+
494+
pub fn max_area_of_island(grid: Vec<Vec<i32>>) -> i32 {
495+
let mut visited = vec![vec![false; grid[0].len()]; grid.len()];
496+
497+
let mut res = 0;
498+
for (i, nums) in grid.iter().enumerate() {
499+
for (j, &num) in nums.iter().enumerate() {
500+
if !visited[i][j] && num == 1 {
501+
let mut count = 0;
502+
Self::bfs(&grid, &mut visited, (i as i32, j as i32), &mut count);
503+
res = res.max(count);
504+
}
505+
}
506+
}
507+
508+
res
509+
}
510+
511+
pub fn bfs(grid: &[Vec<i32>], visited: &mut [Vec<bool>], (x, y): (i32, i32), count: &mut i32) {
512+
let mut queue = VecDeque::new();
513+
queue.push_back((x, y));
514+
visited[x as usize][y as usize] = true;
515+
*count += 1;
516+
while let Some((cur_x, cur_y)) = queue.pop_front() {
517+
for (dx, dy) in Self::DIRECTIONS {
518+
let (nx, ny) = (cur_x + dx, cur_y + dy);
519+
if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 {
520+
continue;
521+
}
522+
let (nx, ny) = (nx as usize, ny as usize);
523+
if !visited[nx][ny] && grid[nx][ny] == 1 {
524+
visited[nx][ny] = true;
525+
queue.push_back((nx as i32, ny as i32));
526+
*count += 1;
527+
}
528+
}
529+
}
530+
}
531+
}
532+
```
533+
487534
<p align="center">
488535
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
489536
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /