public class NQueens { private int n; private boolean[][] board;

public NQueens(int n) {
    this.n = n;
    board = new boolean[n][n];
}

public void solve() {
    if (placeQueens(0)) {
        printBoard();
    } else {
        System.out.println('No solution exists');
    }
}

private boolean placeQueens(int col) {
    if (col == n) {
        return true;
    }

    for (int row = 0; row < n; row++) {
        if (isValidPosition(row, col)) {
            board[row][col] = true;
            if (placeQueens(col + 1)) {
                return true;
            }
            board[row][col] = false;
        }
    }

    return false;
}

private boolean isValidPosition(int row, int col) {
    for (int i = 0; i < col; i++) {
        if (board[row][i]) {
            return false;
        }
    }

    for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
        if (board[i][j]) {
            return false;
        }
    }

    for (int i = row, j = col; i < n && j >= 0; i++, j--) {
        if (board[i][j]) {
            return false;
        }
    }

    return true;
}

private void printBoard() {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (board[i][j]) {
                System.out.print('Q ');
            } else {
                System.out.print('. ');
            }
        }
        System.out.println();
    }
}

public static void main(String[] args) {
    NQueens nQueens = new NQueens(8);
    nQueens.solve();
}

}

N皇后问题 Java 代码:回溯法求解

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

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