八皇后问题是一个古老而著名的问题。在8*8的国际象棋上摆放八个皇后,任何两个皇后都不能在同一行,同一列或同一对角线上。推广至回溯法求解n皇后问题。
回溯法其实就是对隐式树的深度优先搜索算法。当搜索到某一节点室时,判断该节点是否包含问题的解,如果包含,就从该节点出发继续探索下去,如果该节点不包含问题的解,则像其父节点回溯。
例:
Input: 4
Output: [
[".Q…", // Solution 1
“…Q”,
“Q…”,
“…Q.”],
["…Q.", // Solution 2
“Q…”,
“…Q”,
“.Q…”]
]
代码
class Solution {
List<List<String>> results = new LinkedList<List<String>>();
public List<List<String>> solveNQueens(int n){
char[][] columns = new char[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
columns[i][j] = '.';
helper(0, columns, n);
return results;
}
//DFS搜索并回溯。从0开始,如果搜索到最后一行也摆放了Q,则算法结束
public void helper(int n, char[][] columns, int m){
if(n == m){
List<String>answer = new LinkedList<String>();
for(int i = 0; i < m; i ++){
String str = new String(columns[i]);
answer.add(str);
}
results.add(answer);
}
else{
for(int i = 0; i < m; i++){
if(check(n, i, columns, m)){
columns[n][i] = 'Q';
helper(n+1, columns, m);
columns[n][i] = '.';
}
}
}
}
//检查是否在同一行,同一列,同一对角线
boolean check(int n, int i, char[][] columns, int m){
for(int row = 0; row < n; row++) {
for(int col = 0; col < m; col++) {
if(columns[row][col] == 'Q' && (n - row == Math.abs(col - i) || col == i))
return false;
}
}
return true;
}
}
Runtime: 4 ms, faster than 55.28% of Java online submissions for N-Queens.
总结:
-代码段:
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
columns[i][j] = ‘.’;
否则会有如下输出:
\u0000 部分表示搜索树没有运行到的地方
- List<List> results = new LinkedList<List>();定义在方法外,没有作为参数传。
- 字符数组转为字符串: String str = new String(columns[i]);
- DFS算法:
DFS(){
for(){
DFS()
}
}