Flood Fill

An interactive, step-by-step visualisation of Flood Fill.

Category
Recursion
Time complexity
O(cells)
Space complexity
O(cells) stack

Pseudocode

fill(x, y):
  if out of bounds or wall or visited: return
  mark visited
  fill(x±1, y), fill(x, y±1)

Reference implementation

def fill(grid, x, y, visited):
    if not in_bounds(x, y) or grid[y][x] == WALL or (x, y) in visited:
        return
    visited.add((x, y))
    for dx, dy in [(1,0),(-1,0),(0,1),(0,-1)]:
        fill(grid, x+dx, y+dy, visited)

Open the interactive Flood Fill visualisation →