DEV Community

Anubhav Ranjan
Anubhav Ranjan

Posted on

LeetCode Flood Fill Solved — DFS Clicked at 1 AM 😴

🧩 The Problem: Flood Fill (LeetCode #733)
You’re given a 2D image represented as a grid, where each cell has a pixel value.
Starting from a pixel (sr, sc), you need to replace all connected pixels of the same color with a new color — just like the paint bucket tool in MS Paint!

🔍 Approach: Depth-First Search (DFS)
Store the original color of the starting pixel.

Use DFS to visit all 4-directionally connected cells of the same color.

Replace their color after DFS completes.

Track visited cells to avoid infinite recursion.

public static int[][] floodFill(int[][] image, int sr, int sc, int color) {
    int n = image.length, m = image[0].length;
    int initialColor = image[sr][sc];
    boolean[][] vis = new boolean[n][m];
    dfs(image, sr, sc, initialColor, n, m, vis);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (vis[i][j]) image[i][j] = color;
    return image;
}

private static void dfs(int[][] image, int r, int c, int color, int n, int m, boolean[][] vis) {
    if (r < 0 || c < 0 || r >= n || c >= m || vis[r][c] || image[r][c] != color) return;
    vis[r][c] = true;
    dfs(image, r+1, c, color, n, m, vis);
    dfs(image, r-1, c, color, n, m, vis);
    dfs(image, r, c+1, color, n, m, vis);
    dfs(image, r, c-1, color, n, m, vis);
}

Enter fullscreen mode Exit fullscreen mode

💡 Takeaways
Perfect problem to learn 2D grid traversal + DFS

Similar to: Number of Islands, Surrounded Regions

Great for coding interviews and CodeSignal tests (Visa, Uber, etc.)

💬 What I Learned:
Matrix problems need boundary checks + visited tracking

Visualizing as a graph helped a lot!

Solving this gave me the confidence to tackle Number of Islands next

📢 Let’s Connect
I’m sharing my DSA progress + ChatGPT-based workflows every day on Dev.to.
Drop your thoughts, optimizations, or alternate solutions below 👇

Top comments (0)