From 0dc7f2f76565da3796830987274f7e8c7e2e4002 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 16:56:54 +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.=E5=B9=BF=E6=90=9C=E7=89=88.md=20for=20golang?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 45 ++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index a7dd117b..5c77ed05 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -321,11 +321,54 @@ function numIslands2(grid: string[][]): number { } ``` +### Go + +```go + +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + +func numIslands(grid [][]byte) int { + res := 0 + + visited := make([][]bool, len(grid)) + for i := 0; i < len(grid); i++ { + visited[i] = make([]bool, len(grid[0])) + } + + for i, rows := range grid { + for j, v := range rows { + if v == '1' && !visited[i][j] { + res++ + bfs(grid, visited, i, j) + } + } + } + return res +} + +func bfs(grid [][]byte, visited [][]bool, i, j int) { + queue := [][2]int{{i, j}} + visited[i][j] = true // 标记已访问,循环中标记会导致重复 + 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' && !visited[x][y] { + visited[x][y] = true + queue = append(queue, [2]int{x, y}) + } + } + } +} +``` ### Rust ```rust - use std::collections::VecDeque; impl Solution { const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; From 26fc4c41720aee859956309caa97bd6434120840 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 16:58:01 +0800 Subject: [PATCH 2/2] =?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?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 5c77ed05..85471f73 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -199,7 +199,9 @@ class Solution { ### Python + BFS solution + ```python class Solution: def __init__(self): @@ -240,6 +242,7 @@ class Solution: ``` ### JavaScript + ```javascript var numIslands = function (grid) { let dir = [[0, 1], [1, 0], [-1, 0], [0, -1]]; // 四个方向 @@ -324,7 +327,6 @@ function numIslands2(grid: string[][]): number { ### Go ```go - var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} func numIslands(grid [][]byte) int {