大家好,在我的一些大学作业中,我发现需要检查二维数组(网格)中的相邻单元格。我使用的解决方案是使用异常的一些 hack,我正在寻找一种方法来清理它,而不需要像我的一些同学那样加载 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
}
}
我不寒而栗地想到使用异常来使我的代码工作的效率低下的原因,所以我正在寻找关于如何在不牺牲可读性的情况下从我的代码中消除对异常的依赖的建议,以及如何我可以使这个代码段总体上更有效率。提前致谢。
最佳答案
你可以试试这个。 首先决定网格的大小假设它是 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]
}
}
你可以在 2 个循环中完成它。
关于java - 在 Java 中检查二维数组中邻居的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4120609/