From 0134c6c13c2543eb4b7ffb1ca83056b4e0f0be3f Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 19:30:02 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E6=B7=B1=E6=90=9C=E7=89=88.md=20about?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.深搜版.md | 36 +++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index f610e323..aaead2a7 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -279,6 +279,42 @@ class Solution: return result ``` +Rust: + + +use std::collections::VecDeque; +impl Solution { + const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; + pub fn num_islands(grid: Vec>) -> i32 { + let mut visited = vec![vec![false; grid[0].len()]; grid.len()]; + let mut res = 0; + for (i, chars) in grid.iter().enumerate() { + for (j, &c) in chars.iter().enumerate() { + if !visited[i][j] && c == '1' { + res += 1; + Self::dfs(&grid, &mut visited, (i as i32, j as i32)); + } + } + } + res + } + + pub fn dfs(grid: &Vec>, visited: &mut Vec>, (x, y): (i32, i32)) { + 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; + } + let (nx, ny) = (nx as usize, ny as usize); + if grid[nx][ny] == '1' && !visited[nx][ny] { + visited[nx][ny] = true; + Self::dfs(grid, visited, (nx as i32, ny as i32)); + } + } + } + +} +

From b751d1f24d19daba1ff3b3ce4c39377d6d187a74 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 19:30:59 +0800 Subject: [PATCH 2/2] Update --- problems/0200.岛屿数量.深搜版.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index aaead2a7..905c0979 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -282,7 +282,7 @@ class Solution: Rust: -use std::collections::VecDeque; +```rust impl Solution { const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; pub fn num_islands(grid: Vec>) -> i32 { @@ -312,8 +312,8 @@ impl Solution { } } } - } +```