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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jmspan/article/details/51468669

原题网址: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<row; i++) {
            if (rows[i] == col) return true;
            if (i-rows[i] == row-col) return true;
            if (i+rows[i] == row+col) return true;
        }
        return false;
    }
    private void find(int[] queens, int step) {
        if (step == queens.length) {
            nQueens ++;
            return;
        }
        for(int i=0; i<queens.length; i++) {
            if (isConflict(queens, step, i)) continue;
            queens[step] = i;
            find(queens, step+1);
        }
    }
    public int totalNQueens(int n) {
        int[] queens = new int[n];
        find(queens, 0);
        return nQueens;
    }
}

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

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<n; i++) {
            if (((slot >> i) & 1) != 0) continue;
            int ncol = col | (1<<i);
            int nleft = (left | (1<<i)) << 1;
            int nright = (right | (1<<i)) >> 1;
            find(step+1, n, ncol, nleft, nright);
        }
    }
    public int totalNQueens(int n) {
        find(0, n, 0, 0, 0);
        return total;
    }
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页