So I have WPF c# app that have canvas to draw in (drawing is changing fill of Rectangles, for example there is 128x128 rectangles) flood fill alghoritm, it causes StackOverflow if there is too big amount of rectangles than some value (example. 128x128). And I want to upgrade this script to work in any size of draw area. I read some of questions like this, but I still don't know how to repair it and I need help to this specific script cause drawing here is a bit different than normal drawing (this is Pixel Art creator). So this is my alghoritm.
public static void FloodFIll(int x, int y, Brush color, Brush colorToReplace)
{
if (selectedTool == AvailableTools.FillBucket)
{
if (x < 1 || x > PixiManager.drawAreaSize) return;
if (y < 1 || y > PixiManager.drawAreaSize) return;
if (PixiManager.FieldCords(x, y).Fill != color)
{
if (PixiManager.FieldCords(x, y).Fill == colorToReplace)
{
PixiManager.FieldCords(x, y).Fill = color;
FloodFIll(x, y - 1, color, colorToReplace);
FloodFIll(x + 1, y, color, colorToReplace);
FloodFIll(x, y + 1, color, colorToReplace);
FloodFIll(x - 1, y, color, colorToReplace);
}
}
}
}
Here's a none recursive version of your algorithm.
public static void FloodFIll(int x, int y, Brush color, Brush colorToReplace)
{
if (selectedTool != AvailableTools.FillBucket)
{
return;
}
var stack = new Stack<Tuple<int, int>>();
stack.Push(Tuple.Create(x, y));
while(stack.Count > 0)
{
var point = stack.Pop();
if (point.Item1 < 1 || point.Item1 > PixiManager.drawAreaSize) continue;
if (point.Item2 < 1 || point.Item2 > PixiManager.drawAreaSize) continue;
if (PixiManager.FieldCords(point.Item1, point.Item2).Fill == color) continue;
if (PixiManager.FieldCords(point.Item1, point.Item2).Fill == colorToReplace)
{
PixiManager.FieldCords(point.Item1, point.Item2).Fill = color;
stack.Push(Tuple.Create(point.Item1, point.Item2 - 1));
stack.Push(Tuple.Create(point.Item1 + 1, point.Item2));
stack.Push(Tuple.Create(point.Item1, point.Item2 + 1));
stack.Push(Tuple.Create(point.Item1 - 1, point.Item2));
}
}
}
Though you might what to create your own class instead of using Tuple
.