mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 1020.飞地的数量.md about golang
This commit is contained in:
@ -491,6 +491,60 @@ class Solution:
|
|||||||
return ans
|
return ans
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Go
|
||||||
|
|
||||||
|
dfs:
|
||||||
|
|
||||||
|
```go
|
||||||
|
var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}
|
||||||
|
var count int = 0
|
||||||
|
|
||||||
|
func numEnclaves(grid [][]int) int {
|
||||||
|
rows, cols := len(grid), len(grid[0])
|
||||||
|
// 行
|
||||||
|
for i := range grid[0] {
|
||||||
|
if grid[0][i] == 1 {
|
||||||
|
dfs(grid, 0, i)
|
||||||
|
}
|
||||||
|
if grid[rows-1][i] == 1 {
|
||||||
|
dfs(grid, rows-1, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 列
|
||||||
|
for j := range grid {
|
||||||
|
if grid[j][0] == 1 {
|
||||||
|
dfs(grid, j, 0)
|
||||||
|
}
|
||||||
|
if grid[j][cols-1] == 1 {
|
||||||
|
dfs(grid, j, cols-1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
count = 0
|
||||||
|
for i := range grid {
|
||||||
|
for j := range grid[0] {
|
||||||
|
if grid[i][j] == 1 {
|
||||||
|
dfs(grid, i, j)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
func dfs(grid [][]int, i, j int) {
|
||||||
|
grid[i][j] = 0
|
||||||
|
count++
|
||||||
|
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 {
|
||||||
|
dfs(grid, x, y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Rust
|
### Rust
|
||||||
|
|
||||||
dfs:
|
dfs:
|
||||||
|
Reference in New Issue
Block a user