n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
class Solution {
List<List<String>> res = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
back(new int[n], n, 0);
return res;
}
public void back(int[] empress, int n, int index) {
if(index == n) {
List<String> one = new ArrayList<>();
for(int i = 0; i < n; i ++) {
StringBuilder sb = new StringBuilder();
for(int j = 0; j < empress[i]; j ++) {
sb.append(".");
}
sb.append("Q");
for(int j = empress[i] + 1; j < n; j ++) {
sb.append(".");
}
one.add(sb.toString());
}
res.add(one);
return;
}
for(int i = 0; i < n; i ++) {
empress[index] = i;
if(isValid(empress, index))
back(empress, n, index + 1);
}
}
public boolean isValid(int[] empress, int index) {
for(int i = 0; i < index; i ++) {
if(empress[i] == empress[index] || (index - i) == Math.abs(empress[index]-empress[i]))
return false;
}
return true;
}
}