我正在解决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;
}
答案 0 :(得分:0)
你意识到循环
while(tempx >= 0 || tempx < 8 || tempy >= 0 || tempy < 8) {
是无限,每个号码tempx
和tempy
是否满意?
你可能想要
while(tempx >= 0 && tempx < 8 && tempy >= 0 && tempy < 8) {