Skip to content

Commit 3057a18

Browse files
Merge pull request youngyangyang04#2405 from fwqaaq/patch-2
Update 0200.岛屿数量.广搜版.md for golang
2 parents 9928779 + 26fc4c4 commit 3057a18

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

problems/0200.岛屿数量.广搜版.md

+46-1
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,9 @@ class Solution {
199199

200200

201201
### Python
202+
202203
BFS solution
204+
203205
```python
204206
class Solution:
205207
def __init__(self):
@@ -240,6 +242,7 @@ class Solution:
240242

241243
```
242244
### JavaScript
245+
243246
```javascript
244247
var numIslands = function (grid) {
245248
let dir = [[0, 1], [1, 0], [-1, 0], [0, -1]]; // 四个方向
@@ -321,11 +324,53 @@ function numIslands2(grid: string[][]): number {
321324
}
322325
```
323326

327+
### Go
328+
329+
```go
330+
var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}
331+
332+
func numIslands(grid [][]byte) int {
333+
res := 0
334+
335+
visited := make([][]bool, len(grid))
336+
for i := 0; i < len(grid); i++ {
337+
visited[i] = make([]bool, len(grid[0]))
338+
}
339+
340+
for i, rows := range grid {
341+
for j, v := range rows {
342+
if v == '1' && !visited[i][j] {
343+
res++
344+
bfs(grid, visited, i, j)
345+
}
346+
}
347+
}
348+
return res
349+
}
350+
351+
func bfs(grid [][]byte, visited [][]bool, i, j int) {
352+
queue := [][2]int{{i, j}}
353+
visited[i][j] = true // 标记已访问,循环中标记会导致重复
354+
for len(queue) > 0 {
355+
cur := queue[0]
356+
queue = queue[1:]
357+
for _, d := range DIRECTIONS {
358+
x, y := cur[0]+d[0], cur[1]+d[1]
359+
if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) {
360+
continue
361+
}
362+
if grid[x][y] == '1' && !visited[x][y] {
363+
visited[x][y] = true
364+
queue = append(queue, [2]int{x, y})
365+
}
366+
}
367+
}
368+
}
369+
```
324370

325371
### Rust
326372

327373
```rust
328-
329374
use std::collections::VecDeque;
330375
impl Solution {
331376
const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)];

0 commit comments

Comments
 (0)