0

I'm having trouble with the flood fill algorithm. I keep getting StackOverflowError error and I can't figure out why. Sometimes it works and sometimes it doesn't. Is there something wrong with my code?

Thanks!

I've tried filling random things in my image and it seems to work for random cases, other times it doesn't.

public void fill(int x, int y, Color c1, Color c2){


    if(x < 0) return;
    if(y < 0) return;
    if(x >= img.getWidth()) return;
    if(y >= img.getHeight()) return;

    if(c1.getRGB()==c2.getRGB()) return;
    if(grid[x][y].getRGB()!=c1.getRGB())return;

    grid[x][y] = c2;

    fill(x+1,y,c1,c2);
    fill(x,y+1,c1,c2);
    fill(x,y-1,c1,c2);
    fill(x-1,y,c1,c2);

}
Dalton
  • 13
  • 2
  • 2
    Q: Why is your `fill()` calling `fill()`? How do you decide at what point it should stop calling itself? What is this function supposed to be doing? The problem is definitely "fill" calling itself recursively ... until you run out of stack :( – paulsm4 Apr 06 '19 at 05:22
  • 3
    Why do this recursively? – Caius Jard Apr 06 '19 at 05:22
  • first you should know what that error means- https://stackoverflow.com/a/214758/8098322 – Onkar Musale Apr 06 '19 at 05:22
  • @paulsm4 I presume he's flood filling by colouring eg white pixel At 100,100 black, then calling fill on the 4 pixels around it (up down left right (99,99 99,101, 101,99 101,101)) to see if they should also be blacked if they're white, lather rinse repeat. Thing is that's a huge recursion, potentially and will easily overflow the stack. – Caius Jard Apr 06 '19 at 05:24
  • See [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Bohemian Apr 06 '19 at 05:25
  • See https://en.m.wikipedia.org/wiki/Flood_fill comment on the naive algorithm "Though easy to understand, the implementation of the algorithm used above is impractical in languages and environments where stack space is severely constrained (e.g. Java applets)." - quite apt. I recommend reading the entire wiki article and having a go at implementing one of the other algorithms instead – Caius Jard Apr 06 '19 at 05:28
  • Why do this recursively??? because it's simplest thing!!!! why ask a useless a question? – gpasch Apr 06 '19 at 05:51
  • Thanks all, especially @Caius Jard, I figured it out. I used the non-recursive method in that Wikipedia article. – Dalton Apr 06 '19 at 05:59
  • @gpasch been a while since you had some time off? :) The question itself isn't useless because the OP could have been under instruction that this *must* be done recursively, perhaps as an academic exercise. This would then have directed answer effort.. – Caius Jard Apr 06 '19 at 07:51

0 Answers0