先来看一下算法思路
看完算法思想和伪代码紧接着来关注真实代码。
http://blog.csdn.net/linhuanmars/article/details/20667175
Now i will give the code and do some annotation.
public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<List<String>>();
helper(n, 0,new int[n], result);
return result;
}
private void helper(int n, int row, int[] columForRow, List<List<String>> result){
if (row == n){
List<String> strlist = new LinkedList<String>();
for (int i = 0; i < n; i++){ //对每一行进行递归
StringBuilder item = new StringBuilder();
for (int j = 0; j < n; j++){ //对每一行的每一元素进行递归
if(columForRow[i] == j) item.append('Q');
//碰到应该被选中的元素则将该位置放置皇后,columForRow[i]=value, value代表的是每一行应该在那里放置皇后,其他位置非皇后
else item.append('.');
}
strlist.add(item.toString());
}
result.add(strlist);
return;
}
for (int k = 0; k < n; k++){
columForRow[row] = k;
if (check(row, columForRow)){
helper(n, row + 1, columForRow, result);
}
}
}
private boolean check(int row, int[] columForRow){
for (int i = 0; i < row; i++){
if(columForRow[row] == columForRow[i] || Math.abs(columForRow[row] - columForRow[i]) == (row - i)) return false;
}
return true;
}
}