Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2404 from fwqaaq/patch-1
Browse files Browse the repository at this point in the history
Update 0200.岛屿数量.深搜版.md
  • Loading branch information
youngyangyang04 authored Jan 15, 2024
2 parents 62fd172 + 26c4004 commit 9928779
Showing 1 changed file with 31 additions and 40 deletions.
71 changes: 31 additions & 40 deletions problems/0200.岛屿数量.深搜版.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,50 +389,41 @@ function numIslands(grid: string[][]): number {
### Go

```go

var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}

func numIslands(grid [][]byte) int {
// 用1标记已访问
visited := make([][]int, len(grid))
for i := 0; i < len(visited); i++{
visited[i] = make([]int, len(grid[0]))
}
res := 0

var bfs func(x, y int)
bfs = func(x, y int){
stack := make([][]int, 0)
stack = append(stack, []int{x, y})
moveX := []int{1, -1, 0, 0}
moveY := []int{0, 0, 1, -1}

for len(stack) != 0{
node := stack[len(stack) - 1]
stack = stack[:len(stack) - 1]

for i := 0; i < 4; i++{
dx := moveX[i] + node[0]
dy := moveY[i] + node[1]
if dx < 0 || dx >= len(grid) || dy < 0 || dy >= len(grid[0]) || visited[dx][dy] == 1{
continue
}
visited[dx][dy] = 1
if grid[dx][dy] == '1'{
stack = append(stack, []int{dx,dy})
}
}
}
}
visited := make([][]bool, len(grid))
for i := 0; i < len(grid); i++ {
visited[i] = make([]bool, len(grid[0]))
}

result := 0
for i := 0; i < len(grid); i++{
for j := 0; j < len(grid[0]); j++{
if visited[i][j] == 0 && grid[i][j] == '1'{
bfs(i, j)
visited[i][j] = 1
result++
}
}
}
for i, rows := range grid {
for j, v := range rows {
if v == '1' && !visited[i][j] {
res++
dfs(grid, visited, i, j)
}
}
}

return res
}

func dfs(grid [][]byte, visited [][]bool, i, j int) {
visited[x][y] = true
for _, d := range DIRECTIONS {
x, y := i+d[0], j+d[1]
if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) {
continue
}
if grid[x][y] == '1' && !visited[x][y] {
dfs(grid, visited, x, y)
}
}

return result
}
```

Expand Down

0 comments on commit 9928779

Please sign in to comment.