Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Flood fill algorithm using C graphics
The flood fill algorithm is a technique used to fill a connected region with a specific color. It starts from a seed pixel and recursively fills all adjacent pixels that have the same color as the original pixel.
Syntax
void floodFill(int x, int y, int newColor, int oldColor);
Note: This example requires Turbo C/C++ or a compatible graphics library with graphics.h support. Modern compilers may need additional setup for graphics functions.
Algorithm Steps
The flood fill algorithm follows these steps −
- Check if the current pixel coordinates are within screen boundaries
- If the current pixel color matches the old color, replace it with new color
- Recursively call flood fill for all four adjacent pixels (up, down, left, right)
- Continue until no more pixels match the old color
Example: Rectangle Flood Fill
Here's a complete implementation that draws a rectangle and fills it using flood fill algorithm −
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
void floodFill(int x, int y, int newColor, int oldColor) {
// Check if current pixel matches the old color
if (getpixel(x, y) == oldColor) {
// Set new color at current pixel
putpixel(x, y, newColor);
// Recursive calls for adjacent pixels
floodFill(x + 1, y, newColor, oldColor); // Right
floodFill(x - 1, y, newColor, oldColor); // Left
floodFill(x, y + 1, newColor, oldColor); // Down
floodFill(x, y - 1, newColor, oldColor); // Up
}
}
int main() {
int gdriver = DETECT, gmode;
// Initialize graphics mode
initgraph(&gdriver, &gmode, "");
// Define rectangle coordinates
int left = 50, top = 50, right = 300, bottom = 300;
// Draw rectangle outline
rectangle(left, top, right, bottom);
// Set fill parameters
int seedX = 55, seedY = 55;
int newColor = 12; // Light red
int oldColor = 0; // Black (background)
// Apply flood fill
floodFill(seedX, seedY, newColor, oldColor);
getch();
closegraph();
return 0;
}
How It Works
Key Points
- The algorithm uses recursion to fill connected pixels of the same color
-
getpixel(x, y)retrieves the color of pixel at coordinates (x, y) -
putpixel(x, y, color)sets the color of pixel at coordinates (x, y) - The seed point must be inside the area to be filled
- Stack overflow can occur with very large regions due to deep recursion
Conclusion
The flood fill algorithm is essential for area filling in computer graphics. It efficiently fills connected regions by recursively processing adjacent pixels, making it useful for paint bucket tools and region coloring applications.
Advertisements
