我正在尝试计算我的瓷砖对象数组中相邻的地雷。该代码适用于边界内网格的任何部分。假设它是一个 10 x 10 数组,如果我选择点 9,8,它会给我一个数组越界异常。如何确保数组会计算数组边缘的相邻地雷,而不会出现 ArrayOutOfBounds 异常?
void countAdjacentMines(int x,int y) {
//Iterate through the array check if there is a mine
for (int i = 0; i < tiles.length; i++) {
for (int j = 0; j < tiles.length; j++) {
if ((tiles[i][j].getMine() == false)) {
int count = 0;
//Search adjacent tiles. at x,y
for (int p = x - 1; p <= x + 1; p++) {
for (int q = y - 1; q <= y + 1; q++) {
if (0 <= p && p < tiles.length && 0 <= q && q < tiles.length) {
if (tiles[p][q].getMine()==true)
count++;
}
tiles[p][q].setCount(count);
}
}
}
} // end for loop rows
} // end for loop columns
} // end countAdjacentMines
最佳答案
创建一个函数
int hasMine(int x, int x)
当(x,y)
持有地雷时返回1,
如果不是或 (x,y) 不是有效单元格,则为 0(它也很有用)
拥有一个 boolean valid (int x, int y)
函数)。
然后,只需执行以下操作:
totalMine = hasMine(x+1,y+1) + hasMine(x+1, y) + hasMine(x+1, y-1) + .... + hasMine(x-1, y-1)
//8 个 hasMine() 调用。
关于java - 我正在构建一个扫雷项目,我需要帮助计算相邻的地雷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110605/