为什么这种洪水填充算法会导致堆栈溢出?
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;
}
到目前为止,这是我的代码,但是当它到达地图末尾时,它会导致堆栈溢出,有人知道如何解决这个问题(可能是一个棘手的情况)吗?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,存在此调用路径:
这是无限递归,因此会出现堆栈溢出。你的支票无法解决这个问题。您必须执行一项额外检查:
即使您已包含上面的额外检查,请注意最大递归深度为
(_mapWidth * _mapHeight)
,即使对于小位图,该深度也可能非常深(例如100×100)。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).首先,您应该确保
target!=replacement
(可以在初始调用“FloodFill”之前完成一次)。然后,只要 _mapWidth 和 _mapHeight 不是特别大(这在很大程度上取决于 _mapLayers 数组的内容),您的算法就可以工作。如果这是一个问题,您应该尝试非递归算法。创建 a和 a
将初始点放入此列表中并运行某种循环,直到 pointList 为空:从列表中取出一个点,像上面一样处理它,而不是上面的原始递归调用,将四个邻居再次放入列表中。
编辑:这是完整的示例,但没有测试它:
编辑2:事实上,这里有一个优化例程的建议:如果插入毫无意义,请避免插入到列表中,所以:
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 aand a
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:
EDIT2: In fact, here is a suggestion to optimize the routine: avoid inserting to the list if inserting gets pointless, so: