题目描述
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