From 1bc7ca5f8f364e5ae560854d32e6b96cb74408ec Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 21 Aug 2023 23:15:44 +0800 Subject: [PATCH] =?UTF-8?q?Update=201020.=E9=A3=9E=E5=9C=B0=E7=9A=84?= =?UTF-8?q?=E6=95=B0=E9=87=8F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1020.飞地的数量.md | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/problems/1020.飞地的数量.md b/problems/1020.飞地的数量.md index 1ef0796d..29c237e5 100644 --- a/problems/1020.飞地的数量.md +++ b/problems/1020.飞地的数量.md @@ -530,6 +530,51 @@ 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 num_enclaves(mut grid: Vec>) -> i32 { + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if (i == 0 || i == grid.len() - 1 || j == 0 || j == grid[0].len() - 1) + && grid[i][j] == 1 + { + // Self::dfs(&mut grid, (i as i32, j as i32)); + Self::bfs(&mut grid, (i as i32, j as i32)); + } + } + } + grid.iter() + .map(|nums| nums.iter().filter(|&&num| num == 1).count() as i32) + .sum() + } + + pub fn bfs(grid: &mut [Vec], (x, y): (i32, i32)) { + let mut queue = VecDeque::new(); + queue.push_back((x, y)); + grid[x as usize][y as usize] = 0; + 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; + } + + if grid[nx as usize][ny as usize] == 0 { + continue; + } + queue.push_back((nx, ny)); + grid[nx as usize][ny as usize] = 0; + } + } + } +} +``` + ## 类似题目