Pathfinding Algorithm
Flood Fill
“The Completionist”
History
Flood Fill is a staple of computer graphics, famous for powering the "Paint Bucket" tool in MS Paint and Photoshop. While usually associated with image manipulation, in a graph context, it is simply a Breadth-First Search that has no brakes.
It doesn't stop when it sees the goal. It keeps going until it has visited every single reachable node. It is the cartographer of algorithms.
How It Works
Flood Fill performs a complete traversal of the connected component.
The Algorithm Step-by-Step
- Start: Pick a seed node.
- Spread: Visit all valid neighbors.
- Recurse/Loop: Repeat for those neighbors.
- Stop: Only stop when there are no unvisited neighbors left.
In Yield, we use this to generate a "Heatmap" or "Dijkstra Map." Instead of finding a path, we assign every tile a number representing its distance from the start. This creates a flow field that can guide hundreds of agents simultaneously.
It touches every pixel or node exactly once. It is linear relative to the size of the reachable area.
Recursion stack or queue size depends on the shape of the area to be filled.
The core data structure powering Flood Fill.
How this algorithm appears during visualization.
Code Walkthrough
Real implementations in multiple programming languages. Select a language to view idiomatic code.
1from collections import deque23def flood_fill(grid: list[list[int]], start: tuple[int, int]) -> dict[tuple[int, int], int]:4 """Flood fill from start, returning distances to all reachable cells."""5 rows, cols = len(grid), len(grid[0])6 distances = {start: 0}7 queue = deque([start])8 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]910 while queue:11 row, col = queue.popleft()12 current_dist = distances[(row, col)]1314 for dr, dc in directions:15 new_row, new_col = row + dr, col + dc16 neighbor = (new_row, new_col)1718 if (0 <= new_row < rows and 0 <= new_col < cols19 and grid[new_row][new_col] == 020 and neighbor not in distances):21 distances[neighbor] = current_dist + 122 queue.append(neighbor)2324 return distancesReal World Use Cases
- 1Paint Bucket tools in graphics editors
- 2Procedural Cave Generation
- 3Determining reachable areas in games
- 4Flow Field pathfinding for swarm AI
- 5Minesweeper (clearing empty squares)
- 6Fluid simulation logic
Key Insights
- It creates a map of the entire space, not just a single path.
- It is useful for pre-calculating movement data.
- It identifies isolated sub-graphs (islands).
- It is visually satisfying to watch.
- It is the brute-force approach to connectivity.
When to Use
Use Flood Fill when you need to analyze the entire map, fill a region, or create a flow field for swarm AI movement.
When NOT to Use
Do not use this for single-agent pathfinding. It is overkill to map the entire world just to walk to the grocery store.