Skip to content

Instantly share code, notes, and snippets.

@lipx1508
Created March 30, 2023 18:45
Show Gist options
  • Save lipx1508/4a86d0da6822939ee9ac7a0ec9490296 to your computer and use it in GitHub Desktop.
Save lipx1508/4a86d0da6822939ee9ac7a0ec9490296 to your computer and use it in GitHub Desktop.
Flood fill algorithm in C (recursive)
/*
Recursive flood algorithm in C (clean and fast approach)
No license, but post the project and tag me if you used it in anything, would love to see it :)
*/
// Libraries
#include <stdio.h>
#include <time.h>
// Screen
unsigned int screen[5][5] = {
{ 0, 5, 5, 5, 0 },
{ 5, 0, 5, 0, 5 },
{ 5, 0, 0, 0, 5 },
{ 5, 0, 0, 0, 5 },
{ 0, 5, 5, 5, 0 },
};
// Puts a character on the screen
void put(int x, int y, unsigned char c) {
if (x >= 0 && x < 5 && y >= 0 && y < 5) {
screen[y][x] = c;
}
}
// Gets a character
int get(int x, int y) {
if (x >= 0 && x < 5 && y >= 0 && y < 5) {
return screen[y][x];
}
return -1;
}
// Flood fill
void flood(int x, int y, unsigned char c, unsigned char o) {
if (get(x, y) != -1 && get(x, y) == o) {
put(x, y, c);
flood(x + 1, y, c, o);
flood(x - 1, y, c, o);
flood(x, y + 1, c, o);
flood(x, y - 1, c, o);
}
}
// Displays
void display() {
for (unsigned int y = 0; y < 5; y++) {
for (unsigned int x = 0; x < 5; x++) {
putchar(screen[y][x] + '0');
putchar(' ');
}
putchar('\n');
}
}
// Main
int main(int argc, char *argv[]) {
clock_t start = clock();
flood(1, 1, 3, get(1, 1));
printf("Finished in %d milliseconds! \n\n", clock() - start);
display();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment