rel1x
rel1x

Reputation: 2441

Error in Flood fill algorithm in Java

I have a problem with Flood fill algorithm, but I haven't got what is this error. I'm writing a program to this guide: http://en.wikipedia.org/wiki/Flood_fill and this is my error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at BucketFill.fill(BucketFill.java:11)
    at BucketFill.fill(BucketFill.java:22)
    at BucketFill.main(BucketFill.java:49)

How I can fix it? What's wrong? My program correct?

My code:

class BucketFill {

    private char[][] pixels;

    public BucketFill(char[][] pixels) {
        this.pixels = pixels;
    }

    public void fill(int x, int y, char newColor, char oldColor) {
        oldColor = pixels[x][y];

        if (x < 0) return;
        if (y < 0) return;
        if (x >= pixels.length) return;
        if (y >= pixels[x].length) return;
        if (newColor == pixels[x][y]) return;
        if (oldColor != pixels[x][y]) return;

        pixels[x][y] = newColor;

        fill(x - 1, y, newColor, oldColor);
        fill(x + 1, y, newColor, oldColor);
        fill(x, y - 1, newColor, oldColor);
        fill(x, y + 1, newColor, oldColor);
    }

    public void inspect() {
        for (int y = 0; y < pixels.length; y++) {
            for (int x = 0; x < pixels[y].length; x++) {
                System.out.print(pixels[y][x]);
            }
            System.out.print("\n");
        }
    }

    public static void main(String argv[]) {
        char pixels[][] =
        {
            { 'O', 'X', 'X', 'X', 'X' },
            { 'X', 'O', 'O', 'O', 'X' },
            { 'X', 'O', '#', 'O', 'X' },
            { 'X', 'O', 'O', 'O', 'X' },
            { 'X', 'X', 'X', 'X', 'X' },
            { 'X', 'X', 'X', '#', '#' },
            { 'X', 'X', 'X', 'X', 'X' }
        };
        BucketFill bucketFill = new BucketFill(pixels);
        bucketFill.fill(0, 0, '*', 'O');
        bucketFill.fill(3, 0, 'O', 'O');
        bucketFill.fill(2, 1, '@', 'O');
        bucketFill.inspect();
    }
}

Upvotes: 0

Views: 257

Answers (1)

pablochan
pablochan

Reputation: 5715

You assign oldColor before you check the array bounds. You have to move it after the checks:

    if (x < 0) return;
    if (y < 0) return;
    if (x >= pixels.length) return;
    if (y >= pixels[x].length) return;
    // now it's safe to assign
    oldColor = pixels[x][y];

Upvotes: 3

Related Questions