我正在尝试为编程挑战网站编写扫雷程序,并且无法检测 2D 数组中的某个元素是否是地雷并增加周围区域。这是我的代码,用于检查数组角落中的地雷并增加周围区域
public void constructPointers(){
int counter = 0;
for(int i = 0; i<row;i++){
for(int j = 0;j<colm;j++){
if(minefield[i][j].equals("*")){
if(i == 0 && j == 0){
int val = Integer.parseInt(minefield[i+1][j]);
val++;
minefield[i+1][j] = "" + val;
val = Integer.parseInt(minefield[i][j+1]);
val++;
minefield[i][j+1] = "" + val;
val = Integer.parseInt(minefield[i+1][j+1]);
val++;
minefield[i+1][j+1] = "" + val;
}
if(i == minefield.length -1 && j == 0){
int val = Integer.parseInt(minefield[i-1][j]);
val++;
minefield[i-1][j] = "" + val;
val = Integer.parseInt(minefield[i][j+1]);
val++;
minefield[i][j+1] = "" + val;
val = Integer.parseInt(minefield[i-1][j+1]);
val++;
minefield[i-1][j+1] = "" + val;
}
if(i == 0 && j == minefield[i].length - 1){
int val = Integer.parseInt(minefield[i+1][j]);
val++;
minefield[i+1][j] = "" + val;
val = Integer.parseInt(minefield[i][j-1]);
val++;
minefield[i][j-1] = "" + val;
val = Integer.parseInt(minefield[i+1][j-1]);
val++;
minefield[i+1][j-1] = "" + val;
}
if(i == minefield.length - 1 && j == minefield[i].length -1){
int val = Integer.parseInt(minefield[i-1][j-1]);
val++;
minefield[i-1][j-1] = "" + val;
val = Integer.parseInt(minefield[i-1][j]);
val++;
minefield[i-1][j] = "" + val;
val = Integer.parseInt(minefield[i][j-1]);
val++;
minefield[i][j-1] = "" + val;
}
if(i == 0){
int val = Integer.parseInt(minefield[i+1][j]);
val++;
minefield[i+1][j] = "" + val;
val = Integer.parseInt(minefield[i][j+1]);
val++;
minefield[i][j+1] = "" + val;
val = Integer.parseInt(minefield[i+1][j+1]);
val++;
minefield[i+1][j+1] = "" + val;
}
}
如果我输入:
*.*
...
*.*
此代码将输出:
* 2 *
2 4 2
* 2 *
我的问题是:如何让我的代码“跳过”相邻的地雷并增加周边区域?如果我输入
*.*
*..
*.*
我希望它输出:
* 3 *
* 5 2
* 3 *
编辑:你们所有人都有很好的答案,但我选择了最佳答案,因为它解决了我没有提到的许多其他问题。谢谢大家的帮助!