Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
做法和N-Queens一样,也是用递归在每一行尝试放一个棋子,并判断是否合法。这里要记录的是方法总数,比N-Queens要简单一点。
public class Solution {
public int totalNQueens(int n) {
int[] result = new int[1];
result[0] = 0;
recursive(result, n, 0, new int[n]);
return result[0];
}
public void recursive(int[] result, int n, int row, int[] places){
if(row == n){
result[0] = result[0] + 1;
return;
}
for(int col = 0; col < n; col++){
if(checkValid(row, col, places)){
places[row] = col;
recursive(result, n, row + 1, places);
}
}
}
public boolean checkValid(int row, int col, int[] places){
for(int i = 0; i < row; i++){
if(col == places[i])
return false;
if((row - i) == Math.abs(col - places[i]))
return false;
}
return true;
}
}