First of all, you should make sure that target!=replacement
(can be done once before the inital call of 'FloodFill'). Then, your algo may work, as long as _mapWidth and _mapHeight are not extraordinary large (it depends heavily on the content of your _mapLayers array). If this is a problem, you should try a non-recursive algorithm. Create a
class Point
{
public int x, y;
public Point(int newX, int newY)
{
x=newX;
y=newY;
}
}
and a
List<Point> pointList;
Put the initial point into this list and run some kind of loop until pointList is empty: take one point out of the list, process it like above and instead of the original recursive call above put the four neighbours again into the list.
EDIT: here is the complete example, did not test it, though:
void FloodFill2(int layer, int xStart, int yStart, int target, int replacement)
{
if(target==replacement)
return;
List<Point> pointList = new List<Point>();
pointList.Add(new Point(xStart,yStart));
while(pointList.Count>0)
{
Point p = pointList[pointList.Count-1];
pointList.RemoveAt(pointList.Count-1);
if (p.x < 0) continue;
if (p.y < 0) continue;
if (p.x >= _mapWidth) continue;
if (p.y >= _mapHeight) continue;
if (_mapLayers[layer, p.x, p.y] != target) continue;
_mapLayers[layer, p.x, p.y] = replacement;
pointList.Add(new Point(p.x - 1, p.y));
pointList.Add(new Point(p.x + 1, p.y));
pointList.Add(new Point(p.x, p.y - 1));
pointList.Add(new Point(p.x, p.y + 1));
}
}
EDIT2: In fact, here is a suggestion to optimize the routine: avoid inserting to the list if inserting gets pointless, so:
if(p.x>=0)
pointList.Add(new Point(p.x - 1, p.y));
if(p.x<_mapWidth-1)
pointList.Add(new Point(p.x + 1, p.y));
if(p.y>=0)
pointList.Add(new Point(p.x, p.y - 1));
if(p.y<_mapHeight-1)
pointList.Add(new Point(p.x, p.y + 1));