【问题标题】:Recursively going through array and counting pixels递归遍历数组并计算像素
【发布时间】:2018-08-12 00:17:53
【问题描述】:

我的任务是创建一个给定位置 (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]) 行。任何想法为什么会发生这种情况以及如何解决它?

【问题讨论】:

  • 什么是像素[行][列]?它是二维矩阵中的变量还是布尔值?
  • 嗯,您用作索引的值似乎超出了数组大小。
  • 怎么不使用变量p?而且由于您没有使用它,所以我看不到“行”和“列”如何随时更改其值...
  • 我很抱歉我缺乏细节。每个像素都是一个布尔值。 True 为黑色像素,false 为白色像素。
  • 你为什么从你的帖子中删除代码?这个问题现在没有足够的细节。

标签: java arrays recursion


【解决方案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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2017-09-03
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多