问题描述
我正在使用Java编写一个简单的绘画应用程序.我正在尝试使用Flood Fill算法的递归实现作为我的存储桶填充"工具.
I am programming a simple paint application using Java. I'm trying to use a recursive implementation of the Flood Fill algorithm as my 'bucket fill' tool.
但是,这个总是给我一个 StackOverFlowError
.(无论我使用桶填充工具"的面积有多小.)
However, this always gives me a StackOverFlowError
. (No matter how small the area that I'm using the 'bucket fill tool' on is).
更改了代码以使其更有效率.还是同样的错误.
代码如下:
public void floodFill(int x, int y, Color targetColor, Color replacementColor) throws AWTException{
pixelColor = robot.getPixelColor(x,y);
g.setColor(replacementColor);
g.fillRect(x, y, 1, 1);
if(robot.getPixelColor(x-1, y).equals(targetColor))
floodFill(x-1, y, targetColor, replacementColor);
if(robot.getPixelColor(x+1, y).equals(targetColor))
floodFill(x+1, y, targetColor, replacementColor);
if(robot.getPixelColor(x, y-1).equals(targetColor))
floodFill(x, y-1, targetColor, replacementColor);
if(robot.getPixelColor(x, y+1).equals(targetColor))
floodFill(x, y+1, targetColor, replacementColor);
}
我想知道该算法是否还有仍然可以使用递归的方式,而不会出现此错误.
I would like to know if there is a way to still use recursion with this algorithm, and not get this error.
如果不是,那么可以在程序中使用该算法的非递归实现吗?
If not, what possible non-recursive implementations of this algorithm are there, that I can use in my program?
推荐答案
只需在功能的开始处检查当前位置及其颜色.
Just check at the beginning of the function the current Position, which color it has.
如果它已经具有replaceColor,那么您已经访问了这一点并可以返回.
If it already has the replacementColor you already visited this point and can return.
public void floodFill(int x, int y, Color targetColor, Color replacementColor) throws AWTException{
{
if(robot.getPixelColor(x, y).equals(replacementColor))
return;
...
}
这篇关于洪水填充算法导致StackOverFlowError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!