1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| func closedIsland(grid [][]int) int { m := len(grid) n := len(grid[0])
for j := 0; j<n; j++ { toWater(grid, 0, j) toWater(grid, m-1, j) }
for i := 0; i<m; i++ { toWater(grid, i, 0) toWater(grid, i, n-1) }
res := 0 for i :=0; i<m; i++ { for j := 0; j<n; j++ { if grid[i][j] == 0 { res++ toWater(grid,i,j) } } }
return res }
func toWater(grid [][]int, i, j int) { m := len(grid) n := len(grid[0])
var dfs func(grid [][]int, r, c int) dfs = func(grid [][]int, r, c int) { if r < 0 || c < 0 || r >=m || c >=n { return } if grid[r][c] == 1 { return }
grid[r][c] = 1
dfs(grid, r, c-1) dfs(grid, r, c+1) dfs(grid, r-1, c) dfs(grid, r+1, c) } dfs(grid, i, j) return }
|