N-Queens女王是安全的无限循环

时间:2016-11-19 10:39:05

标签: java n-queens

我正在解决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;

}

1 个答案:

答案 0 :(得分:0)

你意识到循环

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

无限每个号码tempxtempy是否满意?

你可能想要

while(tempx >= 0 && tempx < 8 && tempy >= 0 && tempy < 8) {
相关问题