Flood Fill Algorithm: Types, Logic, Approaches & Uses | Updated 2025

How the Flood Fill Algorithm Works in Computer Graphics

CyberSecurity Framework and Implementation article ACTE

About author

Priya (Software Engineer )

Priya is a software engineer with a strong background in building scalable applications and optimizing system performance. With years of experience in the tech industry, they enjoy writing about software engineering concepts, open-source contributions, and emerging technologies to help developers grow.

Last updated on 09th Sep 2025| 10380

(5.0) | 32961 Ratings

What is Flood Fill Algorithm?

The Flood Fill algorithm is a region-filling algorithm commonly used in computer graphics to determine and alter the area connected to a given node in a multi-dimensional array. Think of it as the digital equivalent of the “paint bucket” tool found in image editing software. It works by replacing a target color in a bounded area with a new color starting from a seed point and spreading outward. Flood Fill plays a vital role in image processing, coloring regions in GUIs, and solving problems in grid-based games like Minesweeper or Sudoku. It’s fundamentally a traversal technique usually implemented via recursion or stack that visits and updates connected pixels. The Flood Fill algorithm is a graph traversal method used to determine and alter the area connected to a given node in a multi-dimensional array. It’s most commonly known from paint programs like the “bucket fill” tool that fills a contiguous area of the same color with a new color. Flood fill works by starting at a seed point (usually a pixel or cell) and recursively or iteratively spreading out to adjacent points that meet a specific condition, such as having the same color or value. It continues this process until it reaches boundaries where the condition fails.



To Earn Your Web Developer Certification, Gain Insights From Leading Data Science Experts And Advance Your Career With ACTE’s Web Developer Courses Today!


Applications in Graphics and Games

Flood Fill is integral to several real-world and interactive applications:

  • Image Editors: The “bucket fill” tool fills a bounded area with a chosen color.
  • Drawing Applications: Used to fill shapes or polygons with patterns or colors.
  • Game Development: In tile-based games, to detect and fill connected components. To highlight contiguous game zones or mark map boundaries.
  • Maze Solvers and Pathfinders: Filling reachable areas from a point to visualize reachability.
  • Pattern Recognition: Used to identify and mark clusters in images or arrays.
  • Medical Imaging and CAD tools: Useful in segmentation and region marking.

    Subscribe To Contact Course Advisor

    4-way vs 8-way Flood Fill

    Flood Fill algorithms can be classified based on how they define adjacency between cells or pixels. The two most common types are 4-way and 8-way Flood Fill.

    4-Way Flood Fill

      Adjacency Considered: Only four directions – up, down, left, and right.

      Coordinates Checked:

      1. (x-1, y) → left
      2. (x+1, y) → right
      3. (x, y-1) → up
      4. (x, y+1) → down

      Use Case: When diagonal movement is not allowed or not meaningful (e.g., filling a rectangular grid like in maze solving).

      Advantages:

      1. Simpler and faster in many grid-based applications.
      2. Less prone to “bleeding” into diagonally adjacent regions.

      8-Way Flood Fill

        Adjacency Considered: All eight directions – up, down, left, right, and the four diagonals.

        Coordinates Checked:

          All from 4-way plus:

        1. (x-1, y-1) → top-left
        2. (x+1, y-1) → top-right
        3. (x-1, y+1) → bottom-left
        4. (x+1, y+1) → bottom-right

        Use Case: When diagonal adjacency should be included (e.g., in image processing or pixel-based applications).

        Advantages:

      • More complete fill in natural or organic shapes.
      • Covers diagonally connected areas seamlessly.


      • Would You Like to Know More About Web Developer? Sign Up For Our Web Developer Courses Now!


        Recursive Approach

        Recursive flood fill is the most intuitive implementation. It checks the current pixel and recursively calls itself on neighboring pixels that match the original color. The recursive approach to Flood Fill uses Depth-First Search (DFS) to explore connected cells. Starting from a seed point, it checks if the current cell meets the condition (e.g., target color), changes its value, and recursively calls the function on neighboring cells. In 4-way flood fill, the function recurses in four directions (up, down, left, right), while in 8-way, it includes diagonals. A base case ensures the function stops when out of bounds or when the cell doesn’t match the target. Though simple and elegant, this approach can cause stack overflow on large grids without optimization.

        Recursive Approach Article

        Steps:

        • Check if the current pixel is within bounds.
        • If it has the original color, replace it with the new color.
        • Recur for all valid neighbors (4 or 8 directions).
        • Limitations:

        • May cause stack overflow for large areas due to deep recursion.
        • Not suitable for real-time applications unless properly controlled.

        Course Curriculum

        Develop Your Skills with Web Developer Certification Course

        Weekday / Weekend BatchesSee Batch Details

        Iterative Stack-based Approach

        • Uses an explicit stack (LIFO) to simulate recursion and avoid stack overflow.
        • Begins from the seed/start cell, which is pushed onto the stack.
        • While the stack is not empty:

          1. Pop the top cell.
          2. Check if it’s valid (within bounds and matches target condition/color).
          3. Update the cell (e.g., change color or mark as visited).
          4. Push all valid neighboring cells (4-way or 8-way) onto the stack.
        • Avoids recursion limits, making it safer for large grids.
        • Ideal for Depth-First Search (DFS) style exploration.
        • Can be optimized with a visited set or by modifying the grid in place.
        • Slower than BFS in some cases but uses less memory than recursive DFS in deep graphs.


        Are You Interested in Learning More About Web Developer? Sign Up For Our Web Developer Courses Today!


        Color Replacement Logic

        The color replacement logic is the core component of the flood fill algorithm, responsible for identifying and updating all connected cells that share the same initial color. The process begins by capturing the target color at the starting point (seed coordinates). Before any filling occurs, it’s crucial to check if the target color and the replacement color are the same. If they are, the algorithm should exit immediately to prevent unnecessary work or infinite loops. During traversal, whether recursive or iterative, each cell is evaluated to ensure it is within bounds and matches the target color. If both conditions are met, the cell’s color is changed to the replacement color.

        Color Replacement Logic Article

        The algorithm then proceeds to its neighboring cells (in either 4-way or 8-way directions), applying the same checks and replacements. This process continues until all connected cells of the original color have been filled. This logic ensures that only the region connected to the starting cell and having the same original color is updated, preventing “bleeding” into other areas and maintaining fill boundaries. Proper boundary checks and early exit conditions are essential for both correctness and performance.


        Web Development Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

        Algorithm Pseudocode

        Recursive 4-Way Flood Fill:

        • function floodFill(x, y, originalColor, newColor):
        • if (x < 0 or x >= width or y < 0 or y >= height):
        • return
        • if (pixel[x][y] ≠ originalColor):
        • return
        • pixel[x][y] = newColor
        • floodFill(x+1, y, originalColor, newColor)
        • floodFill(x-1, y, originalColor, newColor)
        • floodFill(x, y+1, originalColor, newColor)
        • floodFill(x, y-1, originalColor, newColor)

        Conclusion

        The Flood Fill algorithm is a powerful tool in computer graphics, from simple shape coloring to complex region analysis. While the recursive approach is easy to implement, the iterative method is preferred for robustness and performance. Understanding the principles of neighborhood traversal, color replacement, and boundary handling equips you to use this algorithm in a wide range of applications from gaming to image analysis. Whether you’re building a paint application or a grid-based puzzle solver,Pseudocode mastering flood fill gives you a strong foundation in both graphics and algorithmic logic.

    Upcoming Batches

    Name Date Details
    Web Developer Certification Course

    08 - Sep- 2025

    (Weekdays) Weekdays Regular

    View Details
    Web Developer Certification Course

    10 - Sep - 2025

    (Weekdays) Weekdays Regular

    View Details
    Web Developer Certification Course

    13 - Sep - 2025

    (Weekends) Weekend Regular

    View Details
    Web Developer Certification Course

    14 - Sep - 2025

    (Weekends) Weekend Fasttrack

    View Details