DEV Community

Koray KARA
Koray KARA

Posted on

Understanding and Implementing Flood Fill Algorithm

Introduction
Welcome to my blog post about understanding and implementing the flood fill algorithm!

My LeetCode Preview

Whether you’re just starting out with coding or looking to improve your algorithmic skills, this article will walk you through a specific problem from LeetCode that involves flood fill. I will provide a step-by-step solution guide to help you grasp the concept easily.

Flood fill is a useful technique used in image editing and graphical user interfaces. It allows us to fill a connected area in a picture or grid with a chosen color. In this guide, we’ll focus on a problem where we need to fill a connected area in a grid with a new color.

Image description

The problem gives us a grid, which is like a square divided into smaller squares. Each square has a certain color. We’re given the starting coordinates (row and column) of a specific square in the grid. Our task is to fill the connected region that includes the starting square with a new color. By doing this, we’ll update the grid to show the filled region.

To solve this problem, we’ll look at a provided solution code and explain it in a way that’s easy to understand, even if you’re new to coding. We’ll talk about important ideas like recursion (a process where a function calls itself) and keeping track of which squares we have visited.

So, let’s jump into the problem overview and explore a step-by-step solution guide for mastering the flood fill algorithm. It’s a great tool to have in your coding toolkit, and I’m excited to guide you through it!

**

Problem Overview

**

The problem we are tackling involves the concept of flood fill, which is a technique used to fill a connected region in a grid with a new color. In this specific LeetCode problem, we are given a grid represented as a 2D array. Each cell in the grid contains a specific color.

The task is to fill a connected region in the grid with a new color starting from a given cell. The connected region includes cells that are adjacent to each other either horizontally or vertically. We need to update the grid by replacing the colors of the cells in the connected region with the new color.

To achieve this, we have the following input parameters:

The grid represented as a 2D array.
The coordinates (row and column) of the starting cell.
The new color that should be used to fill the connected region.

Image description

Our goal is to modify the grid in-place by filling the connected region with the new color. It is important to ensure that all the cells in the connected region are updated, while preserving the colors of other unrelated cells.

By understanding the problem requirements and applying the flood fill algorithm, we can efficiently solve this task. In the subsequent sections, we will delve into the provided solution code and explore a step-by-step guide to implement the flood fill algorithm effectively.

**

Understanding the Solution

**

In this section, we will delve into the provided solution code and gain a better understanding of its structure and logic.

The solution code consists of two methods: “floodFill” and “helper.”

The “floodFill” method serves as the entry point of our solution. It takes the input parameters: the grid, starting coordinates, and the new color. Inside this method, we call the “helper” method to perform the actual flood fill operation. Finally, the updated grid is returned as the output.

The “helper” method is a recursive function that carries out the flood fill operation. It takes the following parameters: the grid, the current coordinates, the new color, the original color of the starting cell, and a set named “visited.”

This method performs the flood fill algorithm recursively by following these steps:

Validating Starting Point:

It checks if the current coordinates are within the bounds of the grid. This is done by using boolean variables, such as “rowInBounds” and “colInBounds.” If the starting point is outside the grid boundaries, the algorithm terminates.

Base Cases and Termination Conditions:

The method checks if the current cell has been visited before by using the “visited” set. If the cell has already been visited, the algorithm stops further exploration of that path and returns.
Additionally, the method checks if the color of the current cell matches the original color of the starting cell. If the colors don’t match, the algorithm terminates for that specific path.

Color Matching and Updating:

If the current cell satisfies the above conditions, it means we can update the color of that cell with the new color.

Recursive Calls:

The method makes recursive calls to the “helper” method for the neighboring cells of the current cell. This includes the cells above, below, to the left, and to the right of the current cell. By making these recursive calls, we ensure that we explore and fill all the connected cells that meet the criteria.
By following these steps recursively, the algorithm fills the connected region in the grid with the new color.

In the next section, I will provide a detailed step-by-step solution guide to implement the flood fill algorithm based on the provided solution code.

**

Step-by-Step Solution

**

In this section, we will provide a step-by-step solution guide based on the provided solution code. We will walk through the algorithm and explain each step in detail.

Starting Point Validation

First, we need to validate if the starting coordinates are within the bounds of the grid. This is essential to ensure that we don’t access cells outside the grid boundaries.
We use boolean variables, such as “rowInBounds” and “colInBounds,” to check if the starting coordinates fall within the valid range of rows and columns.
If the starting point is outside the grid boundaries, we can terminate the algorithm.

Base Cases and Termination Conditions

We need to define the base cases that determine when to terminate the recursion and stop the flood fill process for a particular path.
One base case checks if the current cell has already been visited. We use a set called “visited” to keep track of the visited cells. If the cell has been visited before, we stop further exploration along that path and return.
Another base case checks if the color of the current cell matches the original color of the starting cell. If the colors don’t match, we terminate the flood fill process for that specific path.

Color Matching and Updating

If the current cell satisfies the base cases and the color matches the original color of the starting cell, we can update the color of the current cell with the new color.
This step ensures that we fill the connected region with the new color, gradually updating the colors of all cells in the region.

Recursive Calls

After updating the color of the current cell, we make recursive calls to the “helper” method for the neighboring cells (above, below, to the left, and to the right).
These recursive calls enable us to explore and fill all the connected cells that meet the criteria.
By applying the flood fill algorithm recursively, we ensure that the entire connected region is filled with the new color.
This step-by-step guide allows us to implement the flood fill algorithm effectively and update the grid with the new color for the connected region.

In the next section, we will analyze the time and space complexity of the flood fill algorithm and discuss additional resources for further learning.

You can find my complete solution code here.

class Solution {
    public static int[][] floodFill(int[][] image, int sr, int sc, int color) {
        helper(image, sr, sc, color, image[sr][sc], new HashSet<>());
        return image;
    }

    public static void helper(int[][] image, int sr, int sc, int newColor, int color, HashSet<String> visited) {
        boolean rowInBounds = sr >= 0 && sr < image.length;
        boolean colInBounds = sc >= 0 && sc < image[0].length;
        String cell = sr + "," + sc;
        if (!rowInBounds || !colInBounds) return;
        if (visited.contains(cell)) return;
        if(image[sr][sc] != color) return;
        visited.add(cell);
        image[sr][sc] = newColor;
        helper(image, sr + 1, sc, newColor, color, visited);
        helper(image, sr - 1, sc, newColor, color, visited);
        helper(image, sr, sc + 1, newColor, color, visited);
        helper(image, sr, sc - 1, newColor, color, visited);
    }
}
Enter fullscreen mode Exit fullscreen mode

**

Analyzing Time and Space Complexity

**

It is important to analyze the time and space complexity of the flood fill algorithm to understand its efficiency and resource requirements.

Time Complexity: The time complexity of the flood fill algorithm depends on the number of cells in the connected region that need to be filled. In the worst case, we might need to visit and update each cell in the connected region exactly once. Therefore, the time complexity can be expressed as O(N), where N represents the total number of cells in the connected region.

Space Complexity: The space complexity of the flood fill algorithm is determined by the additional memory used during the recursion, particularly for storing the visited cells. In the provided solution code, a HashSet named “visited” is used to keep track of the visited cells. The space complexity can be expressed as O(N), where N represents the total number of cells in the connected region.

Overall, the time and space complexity of the flood fill algorithm are both linear, depending on the size of the connected region. This makes the algorithm efficient for typical grid sizes.

**

Additional Resources

**
To further enhance your understanding of the flood fill algorithm and related concepts, here are some additional resources you can explore:

GeeksforGeeks: Visit the GeeksforGeeks website to find detailed explanations, code examples, and practice problems related to the flood fill algorithm. They offer so many articles and tutorials on algorithms and data structures.

Algorithms, Part I: This online course offered by Princeton University on Coursera covers essential graph algorithms, including flood fill. It provides a comprehensive introduction to algorithms and their applications, with interactive programming assignments to learn better.

“Introduction to Algorithms” by Thomas H. Cormen: This book is a comprehensive guide to algorithms and is widely used in computer science courses. It covers a wide range of topics, including graph algorithms and flood fill, providing in-depth explanations and examples.

LeetCode Explore: LeetCode’s Explore section offers so many problems and articles on different algorithms and data structures. You can find specific topics related to flood fill and practice solving related coding challenges.
You can practice implementing the flood fill algorithm, and explore related algorithms and concepts to enhance your understanding.

Happy learning and happy coding! 🚀💻

**

Conclusion

**

In this blog post, we have explored the flood fill algorithm and its application to a specific problem from LeetCode. By understanding the provided solution code and following the step-by-step solution, you can effectively implement the flood fill algorithm. We have also analyzed the time and space complexity of the algorithm and provided additional resources for further learning.

The flood fill algorithm is a valuable tool in your coding toolkit, enabling you to solve problems related to filling connected regions in grids. Keep practicing and exploring similar algorithms to enhance your algorithmic thinking and problem-solving abilities.

Happy coding!

Top comments (0)