【问题标题】:N-Queens queen is safe infinite loopN-Queens 皇后是安全的无限循环
【发布时间】: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循环中使用||吗?
  • 我试过它仍然给我同样的结果
  • 好的,我发现它现在可以工作了,我添加了代码

标签: java n-queens


【解决方案1】:

你知道循环

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

无限对于每个tempxtempy是否满意?

你可能想要

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多