Java 洪水填充算法(深度优先搜索)
我正在使用Java。Java 洪水填充算法(深度优先搜索),java,Java,我正在使用Java。 我正在开发一个画图程序,“画图罐”工具使用的是泛光填充算法,但它太贵了 代码如下: private int[] dx = { -1, 0, 1, 0 }; private int[] dy = { 0, 1, 0, -1 }; public void floodFill(int x, int y, Color target_color, Color replacement_color) { Stack<Integer[]> stack = new St
我正在开发一个画图程序,“画图罐”工具使用的是泛光填充算法,但它太贵了 代码如下:
private int[] dx = { -1, 0, 1, 0 };
private int[] dy = { 0, 1, 0, -1 };
public void floodFill(int x, int y, Color target_color, Color replacement_color) {
Stack<Integer[]> stack = new Stack<Integer[]>();
if (imageBuffer.getRGB(x, y) == replacement_color.getRGB())
return;
stack.push(new Integer[] { x, y });
while (!stack.isEmpty()) {
Integer[] aux = stack.peek();
imageBuffer.setRGB(aux[0], aux[1], replacement_color.getRGB());
stack.pop();
for (int i = 0; i < 4; i++) {
if (imageBuffer.getRGB(aux[0] + dx[i], aux[1] + dy[i]) == target_color.getRGB())
stack.push(new Integer[] { aux[0] + dx[i], aux[1] + dy[i] });
}
}
}
private int[]dx={-1,0,1,0};
私有int[]dy={0,1,0,-1};
公共空间泛光填充(int x、int y、颜色目标颜色、颜色替换颜色){
堆栈=新堆栈();
if(imageBuffer.getRGB(x,y)=replacement\u color.getRGB())
返回;
push(新整数[]{x,y});
而(!stack.isEmpty()){
整数[]aux=stack.peek();
setRGB(aux[0],aux[1],replacement_color.getRGB());
stack.pop();
对于(int i=0;i<4;i++){
if(imageBuffer.getRGB(aux[0]+dx[i],aux[1]+dy[i])==target_color.getRGB())
push(新整数[]{aux[0]+dx[i],aux[1]+dy[i]});
}
}
}
有人能帮我提高效率吗
执行(对于1020x700像素图像)大约需要1200ms。使用队列算法的基本思想,您可以阅读(+示例) 您可能会找到其他优化和实现,但我找到了这个。不过,您应该自己完成这项工作。一个快速简单(可能很小)的改进是用ArrayDesign替换堆栈
这将允许您指定初始容量,并使代码更为最新。当泛光填充区域包含许多像素时,需要多次扩展堆栈的矢量基线。这是一种浪费——但成本并不是那么高大约一年前,我尝试实施洪水填充算法已有相当一段时间了。我首先尝试了我自己的解决方案,当它们性能不够时,我上网找到了
QuickFill
(实际的算法从页面的一半开始)算法运行良好。它将在半秒内填满我的droid milestone屏幕(480x854)。如果使用较新的硬件(甚至是桌面硬件),它的工作速度可能会更快。当然,您必须将其移植到Java,但这应该不会太难,尤其是如果我能做到的话 我要说的是,您正在进行大量内存分配。为每个像素分配一个新的整数[]
。我可能会使用两堆原语(比如,中的数组列表),以便处理x
和y
,或者至少用int[]
替换Integer[]
如果这还不够,也许一个算法会有所帮助。我认为主要的是你需要一个更好的算法。这是一个很好的资源。您可以进行一些微优化(例如,
replacement\u color.getRGB()
每次都会进行评估,因为它是target\u color.getRGB()
,但我不认为这会有多大区别。