Description:
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.
Solution:
这道题目太经典了,第一轮没做的原因是担心n太大,TLE,但是后来一想,似乎用二进制已经是最快速的了。
具体的做法可以参考Matrix67原始解说。
基本思路就是用二进制来表示三条线(因为N皇后问题,在第k曾就是有三个方向的限制),一条是最简单的竖直方向限制(这个就和车一样),然后是左右两个斜对角。
状态表示完之后,就判断在这三个方向上是否冲突,如果不冲突,则更新状态,递归到下一层。
注:这里debug了好久的一个地方,如果要把一个char数组转换成String,不能用char[].toString(),而应该用new String(char[])
<span style="font-size:18px;">import java.util.*;
public class Solution {
List<List<String>> list;
int n;
char[] char_list;
public List<List<String>> solveNQueens(int n) {
list = new ArrayList<List<String>>();
this.n = n;
int[] choose = new int[n];
char_list = new char[n];
Arrays.fill(char_list, '.');
dfs(0l, 0l, 0l, 0, choose);
return list;
}
int count = 0;
public void dfs(long vertical, long left, long right, int step, int[] choose) {
if (step == n) {
count++;
List<String> chessboard = new ArrayList<String>();
for (int i = 0; i < n; i++) {
char_list[choose[i]] = 'Q';
String str = new String(char_list);
char_list[choose[i]] = '.';
chessboard.add(str);
}
list.add(chessboard);
} else {
for (int i = 0; i < n; i++) {
long line = 1l << i;
if ((vertical & line) > 0 || (left << 1 & line) > 0
|| (right >> 1 & line) > 0)
continue;
choose[step] = i;
dfs((vertical | line), (left << 1 | line), (right >> 1 | line),
step + 1, choose);
}
}
}
}</span>