在Java中检查二维数组中的邻居的更有效方法

Sea*_*her 8 java performance exception multidimensional-array

嘿所有,对于我的一些大学作业,我发现需要检查二维阵列(网格)中的相邻单元格.我使用的解决方案是使用异常的一些黑客攻击,我正在寻找一种方法来清理它,而不需要if像我的一些同学一样的大量语句.我目前的解决方案是

for ( int row = 0; row < grid.length; row++ ) {
    for ( int col = 0; col < grid.length; col++ ) {
        // this section will usually be in a function
        // checks neighbours of the current "cell"
        try {
            for ( int rowMod = -1; rowMod <= 1; rowMod++ ) {
                for ( int colMod = -1; colMod <= 1; colMod++ ) {
                    if ( someVar == grid[row+rowMod][col+colMod] ) {
                        // do something
                    }
                }
            }
        } catch ( ArrayIndexOutOfBoundsException e ) {
            // do nothing, continue
        }
        // end checking neighbours
    }
}
Run Code Online (Sandbox Code Playgroud)

我不禁想到使用异常来使我的代码工作原因的低效率,所以我正在寻找关于如何在不牺牲可读性的情况下从代码中消除对异常的依赖的建议,以及我如何制作这段代码通常更有效率.提前致谢.

Viv*_*vek 21

你可以试试这个.首先确定网格的大小让我们说它是8 X 8并指定MIN_X = 0,MIN_Y = 0,MAX_X = 7,MAX_Y = 7

您的当前位置由thisPosX,thisPosY表示,然后尝试:

int startPosX = (thisPosX - 1 < MIN_X) ? thisPosX : thisPosX-1;
int startPosY = (thisPosY - 1 < MIN_Y) ? thisPosY : thisPosY-1;
int endPosX =   (thisPosX + 1 > MAX_X) ? thisPosX : thisPosX+1;
int endPosY =   (thisPosY + 1 > MAX_Y) ? thisPosY : thisPosY+1;


// See how many are alive
for (int rowNum=startPosX; rowNum<=endPosX; rowNum++) {
    for (int colNum=startPosY; colNum<=endPosY; colNum++) {
        // All the neighbors will be grid[rowNum][colNum]
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以在2个循环完成它.


Sea*_*her 6

所以,rowcol目前包含我要检查的邻居小区的坐标.因此,如果我有一个名为START_OF_GRIDcontains 的类变量0,我的解决方案如下:

int rowStart  = Math.max( row - 1, START_OF_GRID   );
int rowFinish = Math.min( row + 1, grid.length - 1 );
int colStart  = Math.max( col - 1, START_OF_GRID   );
int colFinish = Math.min( col + 1, grid.length - 1 );

for ( int curRow = rowStart; curRow <= rowFinish; curRow++ ) {
    for ( int curCol = colStart; curCol <= colFinish; curCol++ ) {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)


Den*_*ing 3

为什么不能在数组访问之前检查 row+rowMod 和 col+colMod 的有效性?

就像是:

 r=row+rowMod;
 c=col+colMod;
 if (r < 0 || c < 0 || r >= grid.length || c >= grid.length) continue;
Run Code Online (Sandbox Code Playgroud)

或者(不继续):

 if (r >= 0 && c >= 0 && r < grid.length && c < grid.length && 
     someVar == grid[r][c]) { /* do something */ }
Run Code Online (Sandbox Code Playgroud)