力扣:面试题 08.12. 八皇后

class Solution {
    public List> solveNQueens(int n) {
        List> res = new ArrayList<>();
        int[] queens = new int[n];
        Arrays.fill(queens, -1);
        Set colums1 = new HashSet<>();
        Set diagonals1  = new HashSet<>();
        Set diagonals2  = new HashSet<>();
        calculation(res, queens, n, 0, colums1, diagonals1, diagonals2);
        return res;
    }

    private void calculation(List> res, int[] queens , int n , int row,
                             Set colums1, Set diagonals1, Set diagonals2){
        if (row == n){
            List board = generateBoard(queens, n);
            res.add(new ArrayList<>(board));
            return;
        } else {
            for (int i = 0; i < n; i++){
                // 判断边是否已经可以添加
                if (colums1.contains(i)){
                    continue;
                }
                int diagonal1 = row - i;
                if (diagonals1.contains(diagonal1)){
                    continue;
                }
                int diagonal2 = row + i;
                if (diagonals2.contains(diagonal2)){
                    continue;
                }
                queens[row] = i;
                colums1.add(i);
                diagonals1.add(diagonal1);
                diagonals2.add(diagonal2);
                // 判断下一个点
                calculation(res, queens, n, row + 1, colums1, diagonals1, diagonals2);
                // 结果重置
                queens[row] = -1;
                colums1.remove(i);
                diagonals1.remove(diagonal1);
                diagonals2.remove(diagonal2);
            }
        }
    }

    /**
     * 拼接结果
     * @param queens
     * @param n
     * @return
     */
    private List generateBoard(int[] queens, int n ){
        List board = new ArrayList<>();
        for (int i = 0; i < n; i++){
            char[] row = new char[n];
            Arrays.fill(row, '.');
            row[queens[i]] = 'Q';
            board.add(new String(row));
        }
        return board;
    }
}

你可能感兴趣的:(菜鸟刷题记录,算法,leetcode,java,算法)