KatInterview

733. Flood Fill

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Depth-First Search (DFS)

This problem asks us to change the color of a connected area of pixels in an image, starting from a given pixel. This is a classic application of graph traversal algorithms on a grid. The pixels are the nodes, and adjacency (up, down, left, right) defines the edges. We need to find the connected component of pixels with the same color as the starting pixel and update their color.

Solution

Flood Fill in Python

class Solution:
    def floodFill(self, image: list[list[int]], sr: int, sc: int, color: int) -> list[list[int]]:
        original_color = image[sr][sc]
        
        # If the starting pixel's color is the same as the new color,
        # no action is needed. This also prevents infinite recursion.
        if original_color == color:
            return image
        
        rows, cols = len(image), len(image[0])

        def dfs(r: int, c: int):
            # Base cases for recursion:
            # 1. Check if the current coordinates are out of bounds.
            # 2. Check if the pixel color is the one we want to change.
            if not (0 <= r < rows and 0 <= c < cols and image[r][c] == original_color):
                return
            
            # Change the color of the current pixel.
            image[r][c] = color
            
            # Recursively call for the 4-directionally adjacent pixels.
            dfs(r + 1, c) # Down
            dfs(r - 1, c) # Up
            dfs(r, c + 1) # Right
            dfs(r, c - 1) # Left

        # Start the DFS from the given starting pixel.
        dfs(sr, sc)
        
        return image

Flood Fill in Java

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int originalColor = image[sr][sc];
        // If the starting pixel's color is the same as the new color,
        // no action is needed. This also prevents infinite recursion.
        if (originalColor == color) {
            return image;
        }
        dfs(image, sr, sc, originalColor, color);
        return image;
    }

    private void dfs(int[][] image, int r, int c, int originalColor, int newColor) {
        // Base cases for recursion:
        // 1. Check if the current coordinates are out of bounds.
        // 2. Check if the pixel color is the one we want to change.
        if (r < 0 || r >= image.length || c < 0 || c >= image[0].length || image[r][c] != originalColor) {
            return;
        }

        // Change the color of the current pixel.
        image[r][c] = newColor;

        // Recursively call for the 4-directionally adjacent pixels.
        dfs(image, r + 1, c, originalColor, newColor); // Down
        dfs(image, r - 1, c, originalColor, newColor); // Up
        dfs(image, r, c + 1, originalColor, newColor); // Right
        dfs(image, r, c - 1, originalColor, newColor); // Left
    }
}

Flood Fill in C++

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
        int originalColor = image[sr][sc];
        // If the starting pixel's color is the same as the new color,
        // no action is needed. This also prevents infinite recursion.
        if (originalColor == color) {
            return image;
        }
        dfs(image, sr, sc, originalColor, color);
        return image;
    }

private:
    void dfs(vector<vector<int>>& image, int r, int c, int originalColor, int newColor) {
        int rows = image.size();
        int cols = image[0].size();

        // Base cases for recursion:
        // 1. Check if the current coordinates are out of bounds.
        // 2. Check if the pixel color is the one we want to change.
        if (r < 0 || r >= rows || c < 0 || c >= cols || image[r][c] != originalColor) {
            return;
        }

        // Change the color of the current pixel.
        image[r][c] = newColor;

        // Recursively call for the 4-directionally adjacent pixels.
        dfs(image, r + 1, c, originalColor, newColor); // Down
        dfs(image, r - 1, c, originalColor, newColor); // Up
        dfs(image, r, c + 1, originalColor, newColor); // Right
        dfs(image, r, c - 1, originalColor, newColor); // Left
    }
};

Flood Fill in TypeScript

function floodFill(image: number[][], sr: number, sc: number, color: number): number[][] {
    const originalColor = image[sr][sc];
    
    // If the starting pixel's color is the same as the new color,
    // no action is needed. This also prevents infinite recursion.
    if (originalColor === color) {
        return image;
    }

    const rows = image.length;
    const cols = image[0].length;

    const dfs = (r: number, c: number) => {
        // Base cases for recursion:
        // 1. Check if the current coordinates are out of bounds.
        // 2. Check if the pixel color is the one we want to change.
        if (r < 0 || r >= rows || c < 0 || c >= cols || image[r][c] !== originalColor) {
            return;
        }

        // Change the color of the current pixel.
        image[r][c] = color;

        // Recursively call for the 4-directionally adjacent pixels.
        dfs(r + 1, c); // Down
        dfs(r - 1, c); // Up
        dfs(r, c + 1); // Right
        dfs(r, c - 1); // Left
    };

    // Start the DFS from the given starting pixel.
    dfs(sr, sc);

    return image;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.