LeetCode 52. N-Queens II(N皇后)

原题网址:https://leetcode.com/problems/n-queens-ii/

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

方法一:深度优先搜索,使用一维数组保存皇后位置。

public class Solution {
    private int nQueens = 0;
    private boolean isConflict(int[] rows, int row, int col) {
        for(int i=0; i

方法二:深度优先搜索,使用整数来保存皇后位置,使用位移处理行列、对角线的问题。

public class Solution {
    private int total;
    private void find(int step, int n, int col, int left, int right) {
        if (step == n) {
            total ++;
            return;
        }
        int slot = col | left | right;
        for(int i=0; i> i) & 1) != 0) continue;
            int ncol = col | (1<> 1;
            find(step+1, n, ncol, nleft, nright);
        }
    }
    public int totalNQueens(int n) {
        find(0, n, 0, 0, 0);
        return total;
    }
}


你可能感兴趣的:(深度优先搜索,棋盘,行列,冲突,左移,右移,对角线,比特)