【发布时间】:2017-04-03 04:16:36
【问题描述】:
我正在解决 n-queen,但由于某种原因,我遇到了一个问题,while 循环不断循环而没有迭代,tempx 和 tempy 不会按 i/j 上升。结果一直输出0,0
public static boolean isSafe(Board board, int row, int col){
int tempx;
int tempy;
for(int i = -1; i <= 1; i ++){
for(int j = -1; j <= 1; j ++){
try {
tempx = row + i;
tempy = col + j;
while(tempx >= 0 && tempx < board.getRow() && tempy >= 0 && tempy < board.getRow()) {
if(board.getTile(tempx, tempy).isOccupied())
return false;
tempx += i;
tempy += j;
}
} catch(Exception e){}
}
}
return true;
}
编辑: 好的,我想通了,它似乎工作正常,对于任何想知道它的人,如果有更好的方法,请纠正我
public static boolean isSafe(Board board, int row, int col){
int tempx;
int tempy;
for(int i = -1; i <= 1; i ++){
for(int j = -1; j <= 1; j ++){
try {
tempx = row + i;
tempy = col + j;
for(int k = 0; k < board.getRow(); k++){
if(tempx >= 0 && tempx < 8 && tempy >= 0 && tempy < 8) {
if(board.getTile(tempx, tempy).isOccupied() )
return false;
tempx += i;
tempy += j;
}
}
} catch(Exception e){}
}
}
return true;
}
【问题讨论】:
-
检查你的第三个while循环条件,应该是这样的while((tempx >= 0 && tempx = 0 && tempy
-
你真的想在你的
while循环中使用||吗? -
我试过它仍然给我同样的结果
-
好的,我发现它现在可以工作了,我添加了代码