Space
Open
From Fieldwork
Scales
Archive
Used for: Shortest path in a grid, Rotting Oranges, Level-order traversal.
Visual Logic: Imagine a ripple in a pond spreading out. You must process everything at distance 1 before moving to distance 2.
Key Detail: Always check bounds and "seen" status before adding to the queue (or immediately upon popping).
from collections import deque
def bfs_matrix(grid):
rows, cols = len(grid), len(grid[0])
queue = deque()
visited = set()
# 1. Initialize (Add all starting points)
# Example: Find all '2's (rotten oranges)
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
visited.add((r, c))
steps = 0
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # Right, Left, Down, Up
# 2. The Loop
while queue:
# Range(len) is crucial to distinguish "layers" (distance)
for _ in range(len(queue)):
r, c = queue.popleft()
# 3. Check neighbors
for dr, dc in directions:
nr, nc = r + dr, c + dc
# 4. Validate Bounds & Visited
if (0 <= nr < rows and 0 <= nc < cols and
(nr, nc) not in visited and
grid[nr][nc] == 1): # Example condition: Fresh orange
visited.add((nr, nc))
queue.append((nr, nc))
steps += 1
return stepsPractice 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