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.."] ]
比N-Queens II稍微麻烦一点,其实本质是一样的,解法参考N-Queens II 那道题,区别就是在if(row == n)的时候将list加入,注意:如果有标志可以标记的时候,最好在递归最内层加入list,否则容易出错。
注意输出:此题的输出是一个list里包含若干种解法,每种解法是一个String[],起初把每行当做一个String[]了。
Source
public class Solution {
public List<String[]> solveNQueens(int n) {
List<String[]> st = new ArrayList<String[]>();
if(n == 0) return st;
int[] col = new int[n];
backtrack(n, 0, st, col);
return st;
}
public void backtrack(int n, int row, List<String[]> st, int[] col){
if(row == n){
String[] temp = new String[n];
for(int i = 0; i < n; i++){
StringBuffer a = new StringBuffer();
for(int j = 0; j < n; j++){
if(col[i] == j){
a.append("Q");
}
else a.append(".");
}
temp[i] = a.toString();
}
st.add(temp);
return;
}
for(int i = 0; i < n; i++){
col[row] = i;
if(isValid(row, col)){
backtrack(n, row + 1, st, col);
}
}
}
public boolean isValid(int row, int[] col){
for(int i = 0; i < row; i++){
if(col[i] == col[row] || Math.abs(col[row] - col[i]) == row - i)
return false;
}
return true;
}
}
Test
public static void main(String[] args){
int n = 4;
List<String[]> st = new Solution().solveNQueens(n);
for(int i = 0; i < st.size(); i++){
String[] temp = st.get(i);
for(int j = 0; j < temp.length; j++){
System.out.print(temp[j]);
}
System.out.println();
}
}