Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 6, 2024 19:10
Show Gist options
  • Save hongtaoh/98539c389423e7294f848409a1316b91 to your computer and use it in GitHub Desktop.
Save hongtaoh/98539c389423e7294f848409a1316b91 to your computer and use it in GitHub Desktop.
Solution to Leetcode 200 Number of Islands
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
# dfs, recurssion
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
result = 0
def dfs(r, c):
if r<0 or c<0 or r>rows-1 or c>cols-1 or grid[r][c] == '0':
return
# mark as visited
grid[r][c] = '0'
# keep marking up, left, right, down
dfs(r+1, c)
dfs(r, c-1)
dfs(r, c+1)
dfs(r-1, c)
for r in range(0, rows):
for c in range(0, cols):
if grid[r][c] == '1':
result += 1
dfs(r, c)
return result
@hongtaoh
Copy link
Author

hongtaoh commented Oct 7, 2024

dfs() can also be:

def dfs(r, c):
      if (r<0 or c<0 or r>=rows or c>=cols or grid[r][c]=='0'):
          return 
      grid[r][c] = '0'
      # up, down, left, right
      dfs(r-1, c)
      dfs(r+1, c)
      dfs(r, c-1)
      dfs(r, c+1)

@hongtaoh
Copy link
Author

hongtaoh commented Oct 7, 2024

Note that dfs(r-1, c) will propagate to dfs(r-2,c) ...

dfs(r+1,c) will be executed only if all four directions of (r-1,c) are out of bounds or already "0".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment