N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Solution:
public class Solution {
public int result;
public int totalNQueens(int n) {
int[] path = new int[n];
result = 0;
dfs(path, 0);
return result;
}
public void dfs(int[] path, int level){
int n = path.length;
if (level == n) {
result++;
return;
}
for(int i = 0; i < n; i++){
path[level] = i;
if (!isOK(path,level)) continue;
dfs(path, level + 1);
}
}
public boolean isOK(int[] path, int level){
int n = path.length;
boolean[] check = new boolean[n];
for(int i = 0; i < level; i++){
check[path[i]] = true;
if (path[i] + (level - i) < n) check[path[i] + (level - i)] = true;
if (path[i] - (level - i) >= 0) check[path[i] - (level - i)] = true;
}
return check[path[level]] == false;
}
}