Breadth-First Search (BFS) is a foundational algorithm in computer science, and applying it to a grid is a common challenge in coding interviews and game development. In this quick guide, we'll break down how BFS works on a 2D grid in just two minutes.
What is BFS?
BFS explores a graph level by level, starting from a source node and moving outward. On a grid, each cell acts as a node connected to its up, down, left, and right neighbors.
Step-by-Step BFS on Grid
- Initialize: Start with a queue containing the source cell. Mark it as visited.
- Process: While the queue is not empty, pop the front cell.
- Explore: For each valid neighbor (within bounds, not visited, not blocked), add it to the queue and mark visited.
- Repeat: Continue until the queue empties or you find the target.
Key Use Cases
- Finding the shortest path in an unweighted grid (e.g., maze solving).
- Flood-fill algorithms in image processing.
- Level-order traversal in grid-based games.
Code Snippet (Python)
from collections import deque
def bfs_grid(grid, start, target):
rows, cols = len(grid), len(grid[0])
visited = [[False]*cols for _ in range(rows)]
q = deque([start])
visited[start[0]][start[1]] = True
directions = [(0,1), (0,-1), (1,0), (-1,0)]
while q:
r, c = q.popleft()
if (r, c) == target:
return True
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc] and grid[nr][nc] != 1:
visited[nr][nc] = True
q.append((nr, nc))
return False
Remember: BFS ensures you explore all cells at the same distance before moving deeper. Practice with different grids to solidify your understanding.