Skip to content

Instantly share code, notes, and snippets.

@MorrisLaw
Created June 30, 2022 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorrisLaw/93ad76ef9c39521aefd6ca1337f4ce94 to your computer and use it in GitHub Desktop.
Save MorrisLaw/93ad76ef9c39521aefd6ca1337f4ce94 to your computer and use it in GitHub Desktop.
Number of Islands
func numIslands(grid [][]byte) int {
if grid == nil {
return 0
}
var numOfIslands int
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == '1' {
deleteIsland(grid, i, j)
numOfIslands++
}
}
}
return numOfIslands
}
func deleteIsland(grid [][]byte, i int, j int) {
if i < 0 || j < 0 || i >= len(grid) || j >= len(grid[0]) {
return
}
if grid[i][j] == '1' {
grid[i][j] = '0'
deleteIsland(grid, i+1, j)
deleteIsland(grid, i-1, j)
deleteIsland(grid, i, j-1)
deleteIsland(grid, i, j+1)
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment