LeetCode 733: Flood Fill Solution

Master LeetCode problem 733 (Flood Fill), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To solve this problem, we can use a depth-first search (DFS) approach starting from the given starting pixel. We will recursively check the neighboring pixels and update their color if they have the same color as the starting pixel. We will keep track of visited pixels to avoid revisiting them.

  1. Create a helper function dfs to perform the recursive depth-first search.
  2. In the dfs function, check if the current position is within the image boundaries and if the current pixel color matches the starting pixel color.
  3. Update the color of the current pixel and recursively call dfs for its neighboring pixels.
  4. Return the modified image after performing the flood fill.

Time Complexity: O(mn) where m is the number of rows and n is the number of columns in the image. Space Complexity: O(mn) for the recursive call stack and visited array.

:

Solution Code

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int m = image.length;
        int n = image[0].length;
        int oldColor = image[sr][sc];
        if (oldColor != newColor) {
            dfs(image, sr, sc, m, n, oldColor, newColor);
        }
        return image;
    }

    private void dfs(int[][] image, int i, int j, int m, int n, int oldColor, int newColor) {
        if (i < 0 || i >= m || j < 0 || j >= n || image[i][j] != oldColor) {
            return;
        }
        image[i][j] = newColor;
        dfs(image, i + 1, j, m, n, oldColor, newColor);
        dfs(image, i - 1, j, m, n, oldColor, newColor);
        dfs(image, i, j + 1, m, n, oldColor, newColor);
        dfs(image, i, j - 1, m, n, oldColor, newColor);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 733 (Flood Fill)?

This page provides optimized solutions for LeetCode problem 733 (Flood Fill) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 733 (Flood Fill)?

The time complexity for LeetCode 733 (Flood Fill) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 733 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 733 in Java, C++, or Python.

Back to LeetCode Solutions