Space
Open
From Fieldwork
Scales
Archive
Used for: Number of Islands, Max Area of Island, Flood Fill.
Visual Logic: A rat in a maze blindly running down one path until it hits a wall, then backtracking.
Key Detail: Handle the "Base Case" (out of bounds) at the very top of the function to keep the logic clean.
def solve_islands(grid):
rows, cols = len(grid), len(grid[0])
visited = set() # Or modify grid directly to '#' to save space
def dfs(r, c):
# 1. Base Case: Out of bounds or already visited/invalid
if (r < 0 or r >= rows or c < 0 or c >= cols or
(r, c) in visited or grid[r][c] == "0"):
return 0
# 2. Mark visited
visited.add((r, c))
# 3. Recurse (Summing results if needed, e.g., area)
size = 1
size += dfs(r + 1, c)
size += dfs(r - 1, c)
size += dfs(r, c + 1)
size += dfs(r, c - 1)
return size
# 4. Main loop to find disconnected components
max_area = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in visited:
max_area = max(max_area, dfs(r, c))
return max_areaPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode