From 0f1505600e2c0ab505db9111923bad63ab4e41c1 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 19:26:18 +0800 Subject: [PATCH] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 41 +++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 5b9d90aa..8bbedb59 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -240,6 +240,47 @@ class Solution: ``` +### Rust + +```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::bfs(&grid, &mut visited, (i as i32, j as i32)); + } + } + } + res + } + + pub fn bfs(grid: &Vec>, visited: &mut Vec>, (x, y): (i32, i32)) { + let mut queue = VecDeque::new(); + queue.push_back((x, y)); + visited[x as usize][y as usize] = true; + 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 grid[nx][ny] == '1' && !visited[nx][ny] { + visited[nx][ny] = true; + queue.push_back((nx as i32, ny as i32)); + } + } + } + } +} +```