Graph Traversal

Flood Fill Algorithm

A fundamental algorithm for visiting connected components in a grid, often visualized as 'coloring' a region, with applications in image editing and puzzle games.

Flood Fill in Python (DFS)

Here is a Python implementation of the Flood Fill algorithm using a recursive Depth-First Search (DFS) approach.

def flood_fill(image, sr, sc, new_color):
    rows, cols = len(image), len(image[0])
    original_color = image[sr][sc]
    if original_color == new_color:
        return image

    def dfs(r, c):
        if (r < 0 or r >= rows or c < 0 or c >= cols or
                image[r][c] != original_color):
            return

        image[r][c] = new_color
        dfs(r + 1, c)
        dfs(r - 1, c)
        dfs(r, c + 1)
        dfs(r, c - 1)

    dfs(sr, sc)
    return image

AI Coach Hint: The recursive DFS implementation of Flood Fill is elegant but can lead to a stack overflow on very large areas. For production systems, an iterative BFS approach using a queue is often preferred for its stability.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Backtracking Interview Questions
AI-powered interview preparation guide
Ethical Boundary Interview Discussion
AI-powered interview preparation guide
Stack And Queue Implementation Interview Questions
AI-powered interview preparation guide
Work Sample Interview Discussion
AI-powered interview preparation guide