From 8823181498afb51aac908159d0cb1b31caa5b1fc Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 10:41:57 +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 | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/problems/1020.飞地的数量.md b/problems/1020.飞地的数量.md index 679c1ca9..3488777a 100644 --- a/problems/1020.飞地的数量.md +++ b/problems/1020.飞地的数量.md @@ -545,6 +545,66 @@ func dfs(grid [][]int, i, j int) { } ``` +bfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} +var count int = 0 + +func numEnclaves(grid [][]int) int { + rows, cols := len(grid), len(grid[0]) + // 行 + for i := range grid[0] { + if grid[0][i] == 1 { + bfs(grid, 0, i) + } + if grid[rows-1][i] == 1 { + bfs(grid, rows-1, i) + } + } + // 列 + for j := range grid { + if grid[j][0] == 1 { + bfs(grid, j, 0) + } + if grid[j][cols-1] == 1 { + bfs(grid, j, cols-1) + } + } + count = 0 + for i := range grid { + for j := range grid[0] { + if grid[i][j] == 1 { + bfs(grid, i, j) + } + } + } + return count +} + +func bfs(grid [][]int, i, j int) { + queue := [][]int{} + queue = append(queue, []int{i, j}) + grid[i][j] = 0 + count++ + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, d := range DIRECTIONS { + x, y := cur[0]+d[0], cur[1]+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == 1 { + count++ + queue = append(queue, []int{x, y}) + grid[x][y] = 0 + } + } + } +} +``` + ### Rust dfs: