[java] FloodFill

Started by
4 comments, last by Stefpet 23 years, 11 months ago
I''ve made a pretty straight forward recursive floodfill routine as seen below. However, the problem is that it simply quits after n number of iterations. I guess the stack is thinking it had enough. So, what might be the smartest way to solve this in a nice way? Any comment appericiated. Thanks.

public void floodFill(int x, int y)
{
	if (fielddata[y*GAMEFIELD_WIDTH + x] == 0) {
		fielddata[y*GAMEFIELD_WIDTH + x] = 1;
	
		floodFill(x + 1, y);
		floodFill(x - 1, y);
		floodFill(x, y + 1);
		floodFill(x, y - 1);
	}
}
 
Advertisement
does it quit with a stack overflow error or does it just *quit* ? you''re not doing out of bounds checking in that code, maybe that''s the problem?

-goltrpoat



--
Float like a butterfly, bite like a crocodile.

--Float like a butterfly, bite like a crocodile.
There is a border which prevent the floodfill to fill outside the array.

It''s run as an applet, and it simply stops setting calling itself after about 7900 times. The applet still work as it should and it''s possible to start a new fill.

Filling a small(er) area is no problem, it''s always happening when filling a large area.

I''m more into a way to make the floodFill() smarter, maybe using a linked list instead of recursive calls or something.
First, make sure to check both the x and the y variables against the width and the height of the image and not just the (y*width+x) variable against the array size. The way you index your array in the code that you have posted would allow you to start a fill at (102, 3) even thought the area you want to fill is just 100*100. I''m not sure if that bug would cause the algorithm to stop filling before it is finished but it might definitely cause the algorithm to start filling areas that it''s not supposed to fill. Feel free to post the bounds-checking code.

Second, I doubt there''s any faster version of the algorithm than the one you''ve posted (since array operations are really fast in Java compared to object operations) but even if there is, it''s a bad idea to optimize the code before you got the most simple version of it working.

Henry
If the stack overflows due to too many recursive calls, does it throw an exception?

Put it this way, sooner or later the stack will run out if an unlimited amount of recursion is done. How will that appear? (an exception?)

I''ve monitored the x, y values to see there maximum and minimum value, and they''re always within bounds. So that seems not to be a problem.
Well, got this exception. Time to try something else then...

Exception occurred during event dispatching:java.lang.StackOverflowError	at Test.floodFill 

This topic is closed to new replies.

Advertisement