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
| func numIslands(grid [][]byte) int { result := 0
var dfs func(int, int, int)
dfs = func(row int, col int, count int){ if row < 0 || col < 0 || row >= len(grid) || col >= len(grid[0]) { return }
if string(grid[row][col]) == "0" || string(grid[row][col]) == "2" { return }
grid[row][col] = '2' result += count
dfs(row - 1, col, 0) dfs(row, col + 1, 0) dfs(row + 1, col, 0) bfs(row, col - 1, 0) }
for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[0]); j++ { bfs(i, j, 1) } }
return result }
|