Created
October 11, 2023 20:34
-
-
Save guisantos/7f11984c32b553b0403a8a6bd727c49a to your computer and use it in GitHub Desktop.
Flood Fill Algorithm C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int[,] canvas = new int[,] | |
{ | |
{1, 1, 1, 1, 1, 1, 1, 1}, | |
{1, 1, 1, 1, 1, 1, 0, 0}, | |
{1, 0, 0, 1, 1, 0, 1, 1}, | |
{1, 2, 2, 2, 2, 0, 1, 0}, | |
{1, 1, 1, 2, 2, 0, 1, 0}, | |
{1, 1, 1, 2, 2, 2, 2, 0}, | |
{1, 1, 1, 1, 1, 2, 1, 1}, | |
{1, 1, 1, 1, 1, 2, 2, 1} | |
}; | |
PrintCanvas(canvas); | |
Console.WriteLine(); | |
var x = 0; | |
var y = 0; | |
FloodFill(canvas, x, y, canvas[x, y], 5); | |
PrintCanvas(canvas); | |
void FloodFill(int[,] canvas, int x, int y, int prevColor, int newColor) | |
{ | |
if (x >= 8 || y >= 8 || x < 0 || y < 0) | |
{ | |
return; | |
} | |
if (canvas[x, y] != prevColor) | |
{ | |
return; | |
} | |
canvas[x, y] = newColor; | |
FloodFill(canvas, x + 1, y, prevColor, newColor); | |
FloodFill(canvas, x - 1, y, prevColor, newColor); | |
FloodFill(canvas, x, y + 1, prevColor, newColor); | |
FloodFill(canvas, x, y - 1, prevColor, newColor); | |
} | |
void PrintCanvas(int[,] canvas) | |
{ | |
for (int i = 0; i < 8; i++) | |
{ | |
for (int j = 0; j < 8; j++) | |
{ | |
Console.Write(canvas[i, j] + " "); | |
} | |
Console.WriteLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment