Created
August 4, 2022 10:56
-
-
Save makasim/0257d571c9b868038874517510ba84fd to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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