gpt4 book ai didi

java - N-Queens 皇后是安全的无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:09 25 4
gpt4 key购买 nike

我正在解决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(tempx >= 0 || tempx < 8 || tempy >= 0 || tempy < 8) {

对于每个数字tempxtempy是否满足无限

你可能想要

while(tempx >= 0 && tempx < 8 && tempy >= 0 && tempy < 8) {

关于java - N-Queens 皇后是安全的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com