@@ -199,7 +199,9 @@ class Solution {
199
199
200
200
201
201
### Python
202
+
202
203
BFS solution
204
+
203
205
``` python
204
206
class Solution :
205
207
def __init__ (self ):
@@ -240,6 +242,7 @@ class Solution:
240
242
241
243
```
242
244
### JavaScript
245
+
243
246
``` javascript
244
247
var numIslands = function (grid ) {
245
248
let dir = [[0 , 1 ], [1 , 0 ], [- 1 , 0 ], [0 , - 1 ]]; // 四个方向
@@ -321,11 +324,53 @@ function numIslands2(grid: string[][]): number {
321
324
}
322
325
```
323
326
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
+ ```
324
370
325
371
### Rust
326
372
327
373
``` rust
328
-
329
374
use std :: collections :: VecDeque ;
330
375
impl Solution {
331
376
const DIRECTIONS : [(i32 , i32 ); 4 ] = [(0 , 1 ), (1 , 0 ), (- 1 , 0 ), (0 , - 1 )];
0 commit comments