原题链接在此:https://leetcode.com/problems/n-queens/
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.."] ]
这是一道典型的NP问题,基本思路如下就是递归加回溯:
用递归处理子问题,当某一个子问题出错时就回溯到上一层。这类问题的时间复杂度都是指数量级的。
在子问题中,列出一种例子,判断当前情况是否合法,如果不合法就回到上一层,如果合法就DFS到下一层,当填满后就保存此正确结果。然后去掉最后添加的数,列举其他方法。但本题中不需要去掉就是因为此题是用一个一维数组代表棋盘,每个index代表行, value 代表列。
[2,0,1,3] 代表[0,2],[1,0],[2,1],[3,3]上有皇后。
但有几个问题需要注意,首先要注意返回类型是List<List<String>>,也就是List of List,在生成时一定要这么写
List<List<String>> res = new ArrayList<List<String>>();
否则会报错。
其次注意declare helper function 时,argument 要写成
List<List<String>> res
还有就是用到了新的class StringBuilder, 其sb.append("Hello!")和sb.toString()非常好用。
AC Java:
</pre><pre name="code" class="java">public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<List<String>>();
helper(n,0,new int[n],res);
return res;
}
private void helper(int n, int cur, int[] row, List<List<String>> res){
//cur stands for current row index
if(cur == n){
List<String> temp = new ArrayList<>();
for(int j = 0; j<row.length;j++){
StringBuilder sb = new StringBuilder();
for(int i = 0; i<row.length; i++){
if(row[j] != i) {
sb.append(".");
}else{
sb.append("Q");
}
}
temp.add(sb.toString());
}
res.add(temp);
return;
}
//If we haven't reached the end
for(int i = 0; i < n; i++){
row[cur] = i;
if(isValid(cur, row)){
helper(n,cur+1,row,res);
}
}
}
//Check if the current queens position is valid
private boolean isValid(int cur, int[] row){
for(int i = 0;i<cur;i++){
if(row[cur] == row[i] || Math.abs(row[i]-row[cur]) == (cur-i)){
return false;
}
}
return true;
}
}