Given a rectangle, your task to fill this rectangle using flood fill algorithm.
Examples:
Input : rectangle(left = 50, top = 50, right= 100, bottom = 100)
flood( x = 55, y = 55, new_color = 12, old_color = 0)
Output :

Input : rectangle(left = 50, top = 50, right= 200, bottom = 400)
flood( x = 51, y = 51, new_color = 6, old_color = 0)
Output :

Flood fill algorithm fills new color until the
old color match.
Flood fill algorithm:-
// A recursive function to replace previous
// color 'oldcolor' at '(x, y)' and all
// surrounding pixels of (x, y) with new
// color 'newcolor' and
floodfill(x, y, newcolor, oldcolor)
1) If x or y is outside the screen, then
return.
2) If color of getpixel(x, y) is same as
oldcolor, then
3) Recur for top, bottom, right and left.
floodFill(x+1, y, newcolor, oldcolor);
floodFill(x-1, y, newcolor, oldcolor);
floodFill(x, y+1, newcolor, oldcolor);
floodFill(x, y-1, newcolor, oldcolor);
CPP
#include <graphics.h>
#include <stdio.h>
void flood( int x, int y, int new_col, int old_col)
{
if (getpixel(x, y) == old_col) {
putpixel(x, y, new_col);
flood(x + 1, y, new_col, old_col);
flood(x - 1, y, new_col, old_col);
flood(x, y + 1, new_col, old_col);
flood(x, y - 1, new_col, old_col);
}
}
int main()
{
int gd, gm = DETECT;
initgraph(&gd, &gm, "" );
int top, left, bottom, right;
top = left = 50;
bottom = right = 300;
rectangle(left, top, right, bottom);
int x = 51;
int y = 51;
int newcolor = 12;
int oldcolor = 0;
flood(x, y, newcolor, oldcolor);
getch();
return 0;
}
|
Output:-

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!