我正试图为编程挑战网站编写扫雷程序,但我在检测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 *
编辑:你们都有很好的答案,但我选择了最好的答案,因为它解决了我遇到的许多其他问题,我没有提到。谢谢大家的帮助!
只是为您的矿井更新循环提供一个建议:
// You are on a mine
if(minefield[i][j].equals("*")){
// Now go around your current position
for(int tempRow = i-1; tempRow <= i+1; tempRow++) {
for(int tempCol = j-1; tempCol <= j+1; tempCol++) {
// If a valid square and not a mine
if(tempRow >= 0 && tempRow < row &&
tempCol >= 0 && tempCol < colm &&
!minefield[tempRow][tempCol].equals("*"))
{
// Do your update stuff
int val = Integer.parseInt(minefield[tempRow][tempCol]);
val++;
minefield[tempRow][tempCol] = "" + val;
}
}
}
}
这个环可以更容易地扩展到更大的板尺寸。。。
注意:如果不是地雷,我假设雷场被初始化为"0"。否则,第一个CCD_ 1将出现问题。
您可能会发现在每个单元格上迭代更容易,并且对于每个不是地雷的单元格,计算该单元格周围的地雷数量。换句话说,您可以同时计算每个单元格的计数。这可以解决您关于如何处理相邻矿山的问题。
if(minefield[i][j] == "*"){
// do stuff
}
我不明白有什么大不了的,嗯。
编辑
不正确-正如评论中所说:
if(minefield[i][j].equals("*")){
// do stuff, they are equal.
}
附言:不是很有建设性的回答,但我离开是因为有建设性意见。