0

I am implementing a simple Seed fill algorithm using recursive call. The problem is that its throwing this exception on the recursive call:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

I am trying to fill only small spaces, so the Stack size shouldn't be a problem. Can someone figure out, why the exception is being thrown?

The seedfill class

    package rasterops;

import rasterdata.RasterImage;

import java.awt.*;
import java.awt.image.Raster;
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;



public class SeedFill<PixelType> {



    public RasterImage fill(final RasterImage<PixelType> img, final int x, final int y, PixelType borderColor, PixelType fillColor, PixelType bcgColor) {


        RasterImage<PixelType> result = img;

        PixelType color = (PixelType) img.getPixel(x,y);

        if(bcgColor == color || color != borderColor){

            result = result.withPixel(x,y, fillColor);

            fill(img, x+1, y, borderColor, fillColor,bcgColor);
            fill(img, x-1, y, borderColor, fillColor,bcgColor);
            fill(img, x, y+1, borderColor, fillColor,bcgColor);
            fill(img, x, y-1, borderColor, fillColor,bcgColor);

        }


            return result;

        }


    }

The use of the fill() method in Canvas

if(tool == 3){
                        rasterImage = seedfill.fill(rasterImage, e.getX(), e.getY(), 0xffff00, 0x00ff00, 0x2f2f2f);
                        panel.repaint();

                    }
T.Nosek
  • 31
  • 9

1 Answers1

0

I believe you have an issue in your recursion base case.

Here's your if statement: bcgColor == color || color != borderColor

Which means that regardless of what borderColor is if bcgColor is the same as color you will start to fill.

I think you want this to be bcgColor == color && color != borderColor

Because you want to know that both conditions are true before starting to recurse, rather than both being false which is what would be necessary for the or statement to be false.