-7

我创建了一个二维数组(一个Cell[][]网格),每个单元格都包含一个ArrayList名为neighborCells; 现在我正试图找到它的相邻单元格,但我得到了IndexOutOfBoundsException. 你能帮我吗?

ArrayList<Cell> neighborCells = new ArrayList();
for(int i = 0; i < grid.length; i++){
    for(int j = 0; j < grid.length; j++) { //we can also use grid.length since it is the same
        int startPositionX = (i - 1 < 0) ? i : i - 1;
        int startPositionY = (j - 1 < 0) ? j : j - 1;
        int endPositionX =   (i + 1 > grid.length) ? i : i + 1;
        int endPositionY =  (j + 1 > grid.length) ? j : j + 1;
        for (int row = startPositionX; row <= endPositionX; row++) { 
            for (int col = startPositionY; col <= endPositionY; col++) {
                neighborCells.add(grid[row][col]); // here is the error    
            }
        }   
    }
}
4

2 回答 2

3

I found[1] three errors in your example and suggest the following corrections:

1) change the calculation of end positions - which caused your exception - into this

int endPositionX =   (i + 1 >= grid.length) ? i : i + 1;
int endPositionY =  (j + 1 >= grid.length) ? j : j + 1;

2) you need an arraylist for each cell, so change the initial creation of the results down two lines and change it to

grid[i][j].neighborCells = new ArrayList();

3) a cell isn't its own neighbour

if (row!=i || col!=j) {
    grid[i][j].neighborCells.add(grid[row][col]);
}

[1] I ported it to C++, so sorry if there are any mistakes left from porting it back ;)

于 2014-06-06T09:36:23.900 回答
1

这是我用于测试单元类的内容,因为您没有提供您的

public class Cell {
    public Cell( ) {
        list = new ArrayList<Cell>( );
    }

    public void add( Cell cell ) {
        list.add( cell );
    }

    private List<Cell> list;
}

这是一个查找相邻单元格的示例。如果只能有 4 个相邻单元格(上、下、左和右),我不确定为什么还要再嵌套两个 for 循环。摆脱它们对我来说似乎更简单

Cell[][] grid = new Cell[5][5];

for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[i].length; j++) {
        cell[i][j] = new Cell( );
    }
}

for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[i].length; j++) {
        // Cell above
        if (i > 0) cell[i][j].add( cell[i - 1][j] );

        // Cell to the left
        if (j > 0) cell[i][j].add( cell[i][j - 1] );

        // Cell below
        if (i < grid.length - 1) cell[i][j].add( cell[i + 1][j] );

        // Cell to the right
        if (j < grid[i].length - 1) cell[i][j].add( cell[i][j + 1] );
    }
}
于 2014-06-06T15:41:08.520 回答