n皇后问题

题目描述

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[".Q…", // Solution 1
“…Q”,
“Q…”,
“…Q.”],

["…Q.", // Solution 2
“Q…”,
“…Q”,
“.Q…”]

解法(Java)

位操作注意上括号。

public class _51SolveNQueens {
    int total = 0; //n皇后问题共有多少种可能性
	    int[] sol; //每一行哪一列可以放皇后
	    
    public List<List<String>> solveNQueens(int n) {
        sol = new int[n];
        List<List<String>> res = new ArrayList();
        DFS(res, n, 0, 0, 0, 0);
        return res;
    }
    
    //col,d1,d2 分别表示 row 行中列,右斜对角线,左斜对角线不能放置皇后的位置
    private void DFS(List<List<String>> res, int N, int row, int col, int d1, int d2) {
        int avl = ((1 << N) - 1) & ~(col | d1 | d2);     //available positions, bitmask
        while (avl != 0) {
            int p = avl & -avl;         //取出p从右往左第一个1的位置
            avl ^= p;                   //相当于 avl = avl - p
            sol[row] = p;
            if (row == N - 1) {
                List<String> list = new ArrayList();
                for (int i = 0; i < N; i++) {
                    StringBuilder sb = new StringBuilder();
                    for (int c = 0; c < N; c++) {
                        if ((1 << c) == sol[i]) sb.append("Q");
                        else sb.append(".");
                    }
                    list.add(sb.toString());
                }
                total++;
                res.add(list);
            } else {
                DFS(res, N, row + 1, col ^ p, (d1 ^ p) >> 1, (d2 ^ p) << 1);
            }
        }
    }
}

对二进制运算应用到了极致。。。

注:题目及其解法均来源于leetcode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值