Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

解题思路:问题,每步的solution都与前面的solution相关。要满足,当前的位置i没有被前面使用过并且 |x-y| != |x0 -y0|
Java Code:
public int totalNQueens(int n) {
ArrayList solution = new ArrayList ();
return totalNq(solution, 0, n);
}
public int totalNq(ArrayList orders, int level, int n){
int total = 0;
if(level == n) {
return 1;
}else{
for(int col = 0; col < n; col++){
if(!orders.contains(col)){
int j = 0;
while(j < level && Math.abs(j - level) != Math.abs(orders.get(j) - col) ){
j++;
}
if( j == level){
orders.add(level, col);
total +=totalNq(orders, level + 1,n);
orders.remove(level);
}
}
}
}
return total;
}
No comments:
Post a Comment