递归遍历数组并计算像素

时间:2018-08-12 00:17:53

标签: java arrays recursion

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

  

线程“ main”中的异常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])上发生错误。有什么想法为什么会发生这种情况以及如何解决?

1 个答案:

答案 0 :(得分:1)

在代码中,有以下一行:

margin: "60px"

按原样编写代码,if ((rows > pixels.length || cols > pixels[0].length) || (rows < 0 || cols < 0)) rows的长度可能与数组本身相同,这可能导致cols

例如:

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) 数组的rowscols是否超出范围。

相关问题