public class NQueens {

public static void main(String[] args) {
    int n = 4;
    int[][] board = new int[n][n];
    if (solveNQueens(board, 0)) {
        printBoard(board);
    } else {
        System.out.println('No solution exists');
    }
}

public static boolean solveNQueens(int[][] board, int col) {
    if (col >= board.length) {
        return true;
    }
    for (int row = 0; row < board.length; row++) {
        if (isSafe(board, row, col)) {
            board[row][col] = 1;
            if (solveNQueens(board, col + 1)) {
                return true;
            }
            board[row][col] = 0;
        }
    }
    return false;
}

public static boolean isSafe(int[][] board, int row, int col) {
    int i, j;
    for (i = 0; i < col; i++) {
        if (board[row][i] == 1) {
            return false;
        }
    }
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
        if (board[i][j] == 1) {
            return false;
        }
    }
    for (i = row, j = col; i < board.length && j >= 0; i++, j--) {
        if (board[i][j] == 1) {
            return false;
        }
    }
    return true;
}

public static void printBoard(int[][] board) {
    for (int[] row : board) {
        for (int cell : row) {
            System.out.print(cell + ' ');
        }
        System.out.println();
    }
}

}

N皇后问题 Java 代码实现 - 回溯法解题

原文地址: https://www.cveoy.top/t/topic/nW0T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录