N-Queens II
Description
According to N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
public class Solution {
/**
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
public int totalNQueens(int n) {
// write your code here
List<List<String>> results = new LinkedList<>();
if (n <= 0) {
return 0;
}
List<Integer> cols = new ArrayList<>();
helper(results, n, cols);
return results.size();
}
public void helper(List<List<String>> results , int n, List<Integer> cols) {
// reach solution
if (cols.size() == n) {
results.add(Draw(cols));
return;
}
for (int i = 0; i < n; i++) {
if(!isValid(cols, i)){
continue ;
}
cols.add(i) ;
helper(results , n, cols) ;
cols.remove(cols.size()-1) ;
}
}
public boolean isValid(List<Integer> cols , int i) {
// only check rows above current one
int row = cols.size() ;
for(int j =0 ; j < cols.size() ; j++){
if(i == cols.get(j)){
return false ;
}
if(row + i == j + cols.get(j)){
return false ;
}
if(row - i == j - cols.get(j)){
return false ;
}
}
return true;
}
// build solution from temporary chessboard
public List<String> Draw(List<Integer> cols) {
List<String> result = new ArrayList<>();
for (int i = 0; i < cols.size(); i++) {
StringBuilder sb = new StringBuilder() ;
for(int j = 0; j < cols.size(); j++){
sb.append(j == cols.get(i) ? 'Q' : '.') ;
}
result.add(sb.toString()) ;
}
return result;
}
}