# Boundary fill and Flood fill Algorithm | Computer Graphics

In this article, we are going to learn about Boundary-fill algorithm and Flood-fill algorithm in computer graphics.
Submitted by Abhishek Kataria, on August 25, 2018

## Boundary-fill Algorithm

This is an area filling algorithm. This is used where we have to do an interactive painting in computer graphics, where interior points are easily selected. If we have a specified boundary in a single color, then the fill algorithm proceeds pixel by pixel until the boundary color is encountered. This method is called the boundary-fill algorithm.

In this, generally two methods are given that are:

1. 4-connected:
In this firstly there is a selection of the interior pixel which is inside the boundary then in reference to that pixel, the adjacent pixel will be filled up that is top-bottom and left-right.
2. 8-connected:
This is the best way of filling the color correctly in the interior of the area defined. This is used to fill in more complex figures. In this four diagonal pixel are also included with a reference interior pixel (including top-bottom and left right pixels).

### Problem with boundary fill

1. It may not fill regions correctly, if same interior pixels are also displayed in fill color.
2. In 4-connected there is a problem. Sometimes it does not fill the corner pixel as it checks only the adjacent position of the given pixel.

### Algorithm for boundary fill (4-connected)

```Boundary fill (x, y, fill, boundary)
1) Initialize boundary of the region, and variable fill with color.
2) Let the interior pixel(x,y)
(Now take an integer called current and assign it to (x,y))
current=getpixel(x,y)
3) If current is not equal to boundary and current is not equal
to fill then set pixel (x, y, fill)
boundary fill 4(x+1,y,fill,boundary)
boundary fill 4(x-1,y,fill,boundary)
boundary fill 4(x,y+1,fill,boundary)
boundary fill 4(x,y-1,fill,boundary)

4) End.
```

## Flood-fill Algorithm

By this algorithm, we can recolor an area that is not defined within a single color boundary. In this, we can paint such areas by replacing a color instead of searching for a boundary color value. This whole approach is termed as flood fill algorithm. This procedure can also be used to reduce the storage requirement of the stack by filling pixel spans.

### Algorithm for Flood fill algorithm

```floodfill4 (x, y, fillcolor, oldcolor: integer)

begin
if getpixel (x, y) = old color then
begin
setpixel (x ,y, fillcolor)
floodfill4 (x+1, y, fillcolor, oldcolor)
floodfill4 (x-1, y, fillcolor, oldcolor)
floodfill4 (x, y+1, fillcolor, oldcolor)
floodfill4 (x, y-1, fillcolor, oldcolor)
end.
```