参考来源//http://blog.csdn.net/u011095253/article/details/9158473
http://www.cnblogs.com/springfor/p/3870944.html
public class Solution {
//http://blog.csdn.net/u011095253/article/details/9158473
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> res = new ArrayList<String[]>();
int [] loc = new int[n];
if(n<=0) return null;
helper(res,loc,n,0);
return res;
}
private void helper( ArrayList<String[]> res, int[] loc, int n, int curRow){
if(n==curRow) {
printbrd(res, loc,n);
return;}
else{
for(int i=0; i<n; i++){ // test the col position of curRow's queen
loc[curRow] = i;
if(isValid(loc, curRow))
helper(res, loc, n, curRow+1); // move to next row's queen
// else test next i's position
}
}
}
private boolean isValid(int[] loc, int curRow){
// if(curRow==1) return true;
for(int i=0;i<curRow;i++){
if(loc[i]==loc[curRow] || Math.abs(loc[i]-loc[curRow] )==curRow-i)
return false;
}
return true;
}
private void printbrd(ArrayList<String[]> res, int[] loc, int n){
String [] soln = new String [n] ;
for(int i=0;i<n;i++){
String tmp = new String();
for(int j=0;j<n;j++){
if(loc[i]!=j)
tmp += ".";
else
tmp += "Q";
}
soln[i] = tmp;
}
res.add(soln);
}
}
第二道题目就是统计有多少种方法,改高亮处
public class Solution {
int res;
public int totalNQueens(int n) {
res = 0;
if(n<=0) return 0;
int[] loc = new int[n];
helper(n, loc, 0);
return res;
}
public void helper(int n, int[] loc, int curRow){
if(curRow==n) res++;
else{
for(int i=0;i<n;i++){
loc[curRow]=i;
if(isValid(loc, curRow))
helper(n,loc,curRow+1);
}
}
}
public boolean isValid(int [] loc, int curRow){
if(curRow==0) return true;
for(int i=0;i< curRow; i++){
if(loc[i]==loc[curRow]||Math.abs(loc[i]-loc[curRow])==curRow-i)
return false;
}
return true;
}
}