Created
June 30, 2022 12:43
-
-
Save MorrisLaw/93ad76ef9c39521aefd6ca1337f4ce94 to your computer and use it in GitHub Desktop.
Number of Islands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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