LeetCode No52. N皇后 II

题目

n 皇后问题 研究的是如何将 n 个皇后放置在 n × n 的棋盘上,并且使皇后彼此之间不能相互攻击。

给你一个整数 n ,返回 n 皇后问题 不同的解决方案的数量。

示例 1:

输入:n = 4
输出:2
解释:如上图所示,4 皇后问题存在两个不同的解法。

示例 2:

输入:n = 1
输出:1

提示:

1 <= n <= 9

思路

上一道题一样的代码,只是这个直接统计数目即可。

AC代码

点击查看代码
class Solution {
    int cnt;
    Set<Integer> cols;
    Set<Integer> leftLine;
    Set<Integer> rigthLine;

    private List<String> drawGrid(int[] queens, int n) {
        List<String> grid = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            char[] row = new char[n];
            Arrays.fill(row, '.');
            row[queens[i]] = 'Q';
            grid.add(new String(row));
        }
        return grid;
    }

    private void DFS(int row, int n) {
        if( row == n ) {
            cnt ++;
            return ;
        }
        for(int i=0; i<n; i++) {
            if( cols.contains(i) ) {
                continue;
            }
            int left = row - i;
            if( leftLine.contains(left) ) {
                continue;
            }
            int rigth = row + i;
            if( rigthLine.contains(rigth) ) {
                continue;
            }
            cols.add(i);
            leftLine.add(left);
            rigthLine.add(rigth);
            DFS(row+1, n);
            cols.remove(i);
            leftLine.remove(left);
            rigthLine.remove(rigth);
        }
    }

    public int totalNQueens(int n) {
        cnt = 0;
        cols = new HashSet<>();
        leftLine = new HashSet<>();
        rigthLine = new HashSet<>();
        DFS(0, n);
        return cnt;
    }
}
posted @ 2022-05-25 23:03  Asimple  阅读(11)  评论(0编辑  收藏  举报