-1

我的任务是创建一个给定位置 (int x, int y) 的方法,它从该位置扩展并找到数组中与原始位置具有相同颜色的所有像素。我应该递归地找到这个位置,但我不断收到错误:

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:3

代码:

public int sizeOfConnectedComponent(Position p) {
    if ((rows > pixels.length || cols > pixels[0].length) || (rows < 0 || cols < 0)) {
        return 0;
    } else if (!pixels[rows][cols] || visited[rows][cols]) {

        return 0;
    } else {

        visited[rows][cols] = true;

        sizeOfConnectedComponent((new Position(rows - 1, cols)));
        sizeOfConnectedComponent((new Position(rows + 1, cols)));
        sizeOfConnectedComponent((new Position(rows, cols - 1)));
        sizeOfConnectedComponent((new Position(rows, cols + 1)));
        {
            if (visited[rows][cols] == true){
                total++;
            }
        }
    }
    return total;
}

错误发生就行了if (!pixels[rows][cols] || visited[rows][cols])。任何想法为什么会发生这种情况以及如何解决它?

4

1 回答 1

1

在您的代码中,您有以下行:

if ((rows > pixels.length || cols > pixels[0].length) || (rows < 0 || cols < 0))

使用代码,它可能rowscols数组本身的长度相同,这可能会导致ArrayIndexOutOfBoundsException.

例如:

int rows = 3;
int[] pixels = new int[3];

if (rows > pixels.length) { // This evaluates to false and won't return.
    return 0;               // 'rows > pixels.length' is the same as '3 > 3' which equals false.
}                  

pixels[rows]; // Then, when you try to use 'rows' as the index, you get an error because
              // the maximum array index is always array.length-1

所以而不是:

(rows > pixels.length || cols > pixels[0].length)

它应该是:

(rows >= pixels.length || cols >= pixels[0].length)

此外,您不会检查rowsandcols是否超出您的visited数组的范围。

于 2018-08-12T00:51:45.167 回答