# Boundary Fill Algorithm in C and C++

Here you will learn about boundary fill algorithm in C and C++.

Boundary Fill is another seed fill algorithm in which edges of the polygon are drawn. Then starting with some seed any point inside the polygon we examine the neighboring pixels to check whether the boundary pixel is reached. If boundary pixels are not reached, pixels are highlighted and process is continued until boundary pixels are reached.

Also Read: Flood Fill Algorithm in C and C++

4 Connected Region (Image Source)

Following is the algorithm for filling a region in a recursive manner with color specified fill color (f_color) up to a boundary color specified boundary color (b_color)

### Algorithm

1. Create a function named as boundaryfill with 4 parameters (x,y,f_color,b_color).

```void boundaryfill(int x,int y,int f_color,int b_color)
{
if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color)
{
putpixel(x,y,f_color);
boundaryfill(x+1,y,f_color,b_color);
boundaryfill(x,y+1,f_color,b_color);
boundaryfill(x-1,y,f_color,b_color);
boundaryfill(x,y-1,f_color,b_color);
}
}
//getpixel(x,y) gives the color of specified pixel```

2. Call it recursively until the boundary pixels are reached.

3. Stop.

## Program for Boundary Fill Algorithm in C and C++

### C Program

```#include<stdio.h>
#include<graphics.h>
#include<dos.h>

void boundaryfill(int x,int y,int f_color,int b_color)
{
if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color)
{
putpixel(x,y,f_color);
boundaryfill(x+1,y,f_color,b_color);
boundaryfill(x,y+1,f_color,b_color);
boundaryfill(x-1,y,f_color,b_color);
boundaryfill(x,y-1,f_color,b_color);
}
}
//getpixel(x,y) gives the color of specified pixel

int main()
{
int x,y;

printf("Enter x and y positions for circle\n");
scanf("%d%d",&x,&y);

initgraph(&gd,&gm,"c:\\turboc3\\bgi");
boundaryfill(x,y,4,15);
delay(5000);
closegraph();

return 0;
}```

### C++ Program

```#include<iostream.h>
#include<graphics.h>
#include<dos.h>

void boundaryfill(int x,int y,int f_color,int b_color)
{
if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color)
{
putpixel(x,y,f_color);
boundaryfill(x+1,y,f_color,b_color);
boundaryfill(x,y+1,f_color,b_color);
boundaryfill(x-1,y,f_color,b_color);
boundaryfill(x,y-1,f_color,b_color);
}
}
//getpixel(x,y) gives the color of specified pixel

int main()
{
int x,y;
cout<<"Enter x and y positions for circle\n";
cin>>x>>y;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");
boundaryfill(x,y,4,15);
delay(5000);
closegraph();

return 0;
}```

Author Bio:

I am Rahul Maheshwari from India currently pursuing engineering degree in Computer Science. I am passionate about programming and loves to code as much as I can and likes to help people to become better in programming.