Skip to content

Instantly share code, notes, and snippets.

@rtsoy
Created January 2, 2026 15:19
Show Gist options
  • Select an option

  • Save rtsoy/47f669dc5977c1b415473ff175cb722d to your computer and use it in GitHub Desktop.

Select an option

Save rtsoy/47f669dc5977c1b415473ff175cb722d to your computer and use it in GitHub Desktop.
200. Number of Islands
// https://leetcode.com/problems/number-of-islands/
//
// Time: O(n*m)
// Space: O(n*m)
//
// n = number of rows, m = number of columns
// .................... //
func numIslands(grid [][]byte) int {
n, m := len(grid), len(grid[0])
var dfs func(i, j int)
dfs = func(i, j int) {
if i < 0 || i >= n || j < 0 || j >= m || grid[i][j] != '1' {
return
}
grid[i][j] = '0'
dfs(i+1, j)
dfs(i, j+1)
dfs(i-1, j)
dfs(i, j-1)
}
res := 0
for i := range n {
for j := range m {
if grid[i][j] == '1' {
dfs(i, j)
res++
}
}
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment