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.."]
]
分析,这是典型的递归遍历,感觉也不是典型意义上的回溯,只是对每一行,列举所有可能的情况,然后进入下一步递归。
具体这道题,可以用一个一维数组来表示棋盘,下标表示行,内容表示列,这样就确定了每行皇后的位置。
对每一行,尝试把皇后放在每一个位置,如果放置合法,就进去下一层递归。
public class Solution {
public List<String[]> solveNQueens(int n) {
//典型递归题
List<String[]> res = new ArrayList<String[]>();
//一维数组表示棋盘,下标表示行,内容表示列
int[] loc = new int[n];
dfs(res, loc, 0, n);
return res;
}
public void dfs(List<String[]> res, int[] loc, int cur, int n){
if(cur == n)
printBoard(res, loc, n);
else
//分别尝试在当前行各个列放王后
for(int i=0; i<n; i++){
loc[cur] = i;
//如果当前行合法,可以尝试下一行
if(isValid(loc, cur))
dfs(res, loc, cur+1, n);
}
}
public boolean isValid(int[] loc, int cur){
for(int i=0; i<cur; i++){
//检查列,两对角线,行在这里已经保证只有一个
if(loc[i]==loc[cur] || Math.abs(loc[i]-loc[cur])==(cur-i))
return false;
}
return true;
}
//把一维棋盘翻译成结果
public void printBoard(List<String[]> res, int[] loc, int n){
String[] ans = new String[n];
for(int i=0; i<n; i++){
StringBuilder row = new StringBuilder();
for(int j=0; j<n; j++){
//此列放皇后
if(j==loc[i])
row.append("Q");
else
row.append(".");
}
ans[i] = row.toString();
}
res.add(ans);
}
}