Skip to content

Instantly share code, notes, and snippets.

@makasim
Created August 4, 2022 10:56
Show Gist options
  • Save makasim/0257d571c9b868038874517510ba84fd to your computer and use it in GitHub Desktop.
Save makasim/0257d571c9b868038874517510ba84fd to your computer and use it in GitHub Desktop.
func numIslands(grid [][]byte) int {
if len(grid) == 0 {
return 0
} else if len(grid[0]) == 0 {
return 0
}
cols := len(grid)
rows := len(grid[0])
var islands int
var visit func(col, row int)
visit = func(col, row int) {
if col < 0 || col >= cols {
return
}
if row < 0 || row >= rows {
return
}
if grid[col][row] != '1' {
return
}
grid[col][row] = '2'
visit(col+1, row)
visit(col, row+1)
visit(col-1, row)
visit(col, row-1)
}
for col := 0; col < cols; col++ {
for row := 0; row < rows; row++ {
if grid[col][row] == '1' {
islands++
visit(col, row)
}
}
}
return islands
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment