From c7ec1d7705b108257983f1b192126f2bec2888b4 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 22:27:28 +0800 Subject: [PATCH] =?UTF-8?q?Update=200695.=E5=B2=9B=E5=B1=BF=E7=9A=84?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E9=9D=A2=E7=A7=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0695.岛屿的最大面积.md | 47 ++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0695.岛屿的最大面积.md b/problems/0695.岛屿的最大面积.md index 2d25c54c..b8b2ea72 100644 --- a/problems/0695.岛屿的最大面积.md +++ b/problems/0695.岛屿的最大面积.md @@ -484,6 +484,53 @@ impl Solution { } ``` +bfs: + +```rust +use std::collections::VecDeque; +impl Solution { + const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; + + pub fn max_area_of_island(grid: Vec>) -> i32 { + let mut visited = vec![vec![false; grid[0].len()]; grid.len()]; + + let mut res = 0; + for (i, nums) in grid.iter().enumerate() { + for (j, &num) in nums.iter().enumerate() { + if !visited[i][j] && num == 1 { + let mut count = 0; + Self::bfs(&grid, &mut visited, (i as i32, j as i32), &mut count); + res = res.max(count); + } + } + } + + res + } + + pub fn bfs(grid: &[Vec], visited: &mut [Vec], (x, y): (i32, i32), count: &mut i32) { + let mut queue = VecDeque::new(); + queue.push_back((x, y)); + visited[x as usize][y as usize] = true; + *count += 1; + while let Some((cur_x, cur_y)) = queue.pop_front() { + for (dx, dy) in Self::DIRECTIONS { + let (nx, ny) = (cur_x + dx, cur_y + dy); + if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 { + continue; + } + let (nx, ny) = (nx as usize, ny as usize); + if !visited[nx][ny] && grid[nx][ny] == 1 { + visited[nx][ny] = true; + queue.push_back((nx as i32, ny as i32)); + *count += 1; + } + } + } + } +} +``` +