void FloodFill(int layer, int x, int y, int target, int replacement)
{
if (x < 0) return;
if (y < 0) return;
if (x >= _mapWidth) return;
if (y >= _mapHeight) return;
if (_mapLayers[layer, x, y] != target) return;
_mapLayers[layer, x, y] = replacement;
FloodFill(layer, x - 1, y, target, replacement);
FloodFill(layer, x + 1, y, target, replacement);
FloodFill(layer, x, y - 1, target, replacement);
FloodFill(layer, x, y + 1, target, replacement);
return;
}
This is my code so far, but when it reaches the end of the map it causes a Stack Overflow, does anybody know how to solve the problem (probably a tricky condition)?
Notice that this call path exists:
This is an infinite recursion, so you have stack overflow. Your checks can’t deal with this. You have to perform one extra check:
Even if you have included the extra check above, note that the maximum recursion depth is
(_mapWidth * _mapHeight), which can be very deep even for a small bitmap (e.g. 100 x 100).