N 皇后 II (N-Queens II)

 

思路:

// @Title: N 皇后 II (N-Queens II)
// @Author: qisiii
// @Date: 2024-09-21 17:59:38
// @Runtime: 2 ms
// @Memory: 39.5 MB
// @comment: 
// @flag: 
class Solution {
    private int sum=0;
    public int totalNQueens(int n) {
    char[][] matrix = new char[n][n];
        for (char[] row : matrix) {
            Arrays.fill(row, '.');
        }
        dfs( matrix, n, 0);
        return sum;
    }

    private void dfs(char[][] matrix, int n, int row) {
        if (row == n) {
            sum++;
            return;
        }
        for (int j = 0; j < n; j++) {
            if (isValid(row, j,matrix)) {
                matrix[row][j] = 'Q';
                dfs(matrix, n, row + 1);
                matrix[row][j] = '.';
            }
        }
    }

    private boolean isValid(int row, int column, char[][] matrix) {
        for (int j = 0; j < row; j++) {
            if (matrix[j][column] == 'Q') {
                return false;
            }
        }
        for (int i = row - 1, j = column - 1; i >= 0 && j >= 0; i--, j--) {
            if (matrix[i][j] == 'Q') {
                return false;
            }
        }
        for (int i = row - 1, j = column + 1; i >= 0 && j < matrix.length; i--, j++) {
            if (matrix[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18