The problem can be thought of as finding all connected components in a graph. Here, our graph vertices are the cells of the grid, and edges exist between horizontally and vertically adjacent land cells (‘1’s).
visited
boolean grid.visited
array, though we can optimize by marking cells directly in the input grid.Here’s the implementation in Python using the DFS approach:
def numIslands(grid):
if not grid:
return 0
def dfs(grid, r, c):
rows, cols = len(grid), len(grid[0])
if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] == '0':
return
# Mark this cell as '0' to indicate it's visited
grid[r][c] = '0'
# Perform DFS in all 4 directions
dfs(grid, r + 1, c)
dfs(grid, r - 1, c)
dfs(grid, r, c + 1)
dfs(grid, r, c - 1)
rows, cols = len(grid), len(grid[0])
island_count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1':
island_count += 1
dfs(grid, r, c)
return island_count
Is there anything specific you’d like to adjust or any other part you’d like to focus on?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?