N 皇后区回溯

问题描述 投票:0回答:0
public static boolean isSafe(char board[][], int row, int col){
    //only checking upper row because we are filling rows from up

    //vertically up check
    for(int i = row-1; i>=0; i--){
        if(board[i][col] == 'Q'){
            return false;
        }
    }

    // left diagonal check
    for(int i= row-1, j = col-1; i>=0 && j>=0; i--,j--){
        if(board[i][j] == 'Q'){
            return false;
        }
    }

    //right diagonal check
    for(int i= row-1, j= col+1; i>=0 && j<board.length; i--,j++){
        if(board[i][j] == 'Q'){
            return false;
        }
    }

    return true;
}

public static void PrintBoard(char board[][]){
    for(int i=0; i<board.length; i++){
        System.out.print(" CHESS BOARD  ");
        for(int j=0; j<board.length; j++){
            System.out.print(board[i][j] + " ");
        }
        System.out.println();
    }
}

public static void NQueens(char board[][], int row){
    if(row == board.length){
        PrintBoard(board);
        return;
    }

    for(int j=0; j<board.length; j++){
        if(isSafe(board, row, j)){
            board[row][j] = 'Q';
            NQueens(board, row+1);
            board[row][j] = '_';
        }
    }
}

public static void main(String args[]){
    int n = 4;
    char board [][] = new char[n][n];
    NQueens(board, n);
}

请告诉我代码中的错误。它什么都不打印(不打印所需的输出)。

recursion syntax-error backtracking solution n-queens
© www.soinside.com 2019 - 2024. All rights reserved.