Skip to content

Commit 6d50f47

Browse files
committed
增加岛屿数量深搜go版本
1 parent 86a0208 commit 6d50f47

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

problems/kamacoder/0099.岛屿的数量深搜.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,75 @@ if __name__ == '__main__':
326326

327327
### Go
328328

329+
我们使用一个visited数组,记录下那些位置被遍历过。分为两层遍历。初始化一个visited数组和原始的grid一样大,用来记录哪些陆地被遍历过
330+
331+
第一层遍历遍历整个grid数组的元素,遇到陆地,就在对应的visited数组里标记,并且执行深度搜索,深搜的逻辑是把当前位置的4个方向上的位置,全部判断一遍看是不是陆地,如果是,则在这个位置上再执行深搜,达到递归深搜的效果。所以深搜函数里是递归的。
332+
333+
```go
334+
package main
335+
336+
import (
337+
"fmt"
338+
)
339+
340+
func visitIsland(grid [][]int) int {
341+
row := len(grid)
342+
if row == 0 {
343+
return 0
344+
}
345+
visited := make([][]bool, row)
346+
//go的这种初始化方式真的丑陋
347+
for i := 0; i < row; i++ {
348+
visited[i] = make([]bool, len(grid[0]))
349+
}
350+
ans := 0
351+
for i := 0; i < row; i++ {
352+
for j := 0; j < len(grid[0]); j++ {
353+
if grid[i][j] == 1 && !visited[i][j] {
354+
visited[i][j] = true
355+
ans++
356+
visitGrid(grid, visited, i, j)
357+
}
358+
}
359+
}
360+
return ans
361+
}
362+
363+
func visitGrid(grid [][]int, visited [][]bool, x int, y int) {
364+
diff := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
365+
for _, arr := range diff {
366+
nextX := x + arr[0]
367+
nextY := y + arr[1]
368+
if nextX < 0 || nextX >= len(grid) || nextY < 0 || nextY >= len(grid[0]) {
369+
continue
370+
}
371+
if !visited[nextX][nextY] && grid[nextX][nextY] == 1 {
372+
visited[nextX][nextY] = true
373+
visitGrid(grid, visited, nextX, nextY)
374+
}
375+
}
376+
}
377+
378+
func main() {
379+
var row, col int
380+
fmt.Scan(&row, &col)
381+
if row <=0 || col <=0 {
382+
return
383+
}
384+
grid := make([][]int, row)
385+
for i := 0; i < row; i++ {
386+
grid[i] = make([]int, col)
387+
}
388+
for i := 0; i < row; i++ {
389+
for j := 0; j < col; j++ {
390+
fmt.Scan(&grid[i][j])
391+
}
392+
}
393+
//这里必须要打印,不然报错会显示潜在的数组越界
394+
fmt.Println(visitIsland(grid))
395+
}
396+
```
397+
329398
### Rust
330399

331400
### JavaScript

0 commit comments

Comments
 (0)