From d02c6a7d178ed420dfa404e091b6f7da0118185f Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 22:09:24 +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=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0695.岛屿的最大面积.md | 45 ++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/problems/0695.岛屿的最大面积.md b/problems/0695.岛屿的最大面积.md index 9ce4e56c..2d25c54c 100644 --- a/problems/0695.岛屿的最大面积.md +++ b/problems/0695.岛屿的最大面积.md @@ -439,6 +439,51 @@ impl Solution { } ``` +dfs: 版本二 + +```rust +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::dfs(&grid, &mut visited, (i as i32, j as i32), &mut count); + res = res.max(count); + } + } + } + + res + } + + pub fn dfs( + grid: &Vec>, + visited: &mut [Vec], + (x, y): (i32, i32), + count: &mut i32, + ) { + if visited[x as usize][y as usize] || grid[x as usize][y as usize] == 0 { + return; + } + visited[x as usize][y as usize] = true; + *count += 1; + for (dx, dy) in Self::DIRECTIONS { + let (nx, ny) = (x + dx, y + dy); + if nx < 0 || nx >= grid.len() as i32 || ny < 0 || ny >= grid[0].len() as i32 { + continue; + } + Self::dfs(grid, visited, (nx, ny), count); + } + } +} +``` +