Pattern
Pattern
Pattern
Traverse nodes with visited state to explore components, paths, and dependencies.
Build neighbors, mark visited on entry, then traverse with queue or stack.
def dfs(row, col):
if row < 0 or col < 0 or row == rows or col == cols:
return
if (row, col) in visited or grid[row][col] == '0':
return
visited.add((row, col))
dfs(row + 1, col)
dfs(row - 1, col)
dfs(row, col + 1)
dfs(row, col - 1)