Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
解题思路:和上题一样《JAVA语言程序设计》中exerice6-22已经给出了计算count的代码,直接拿来用即可,JAVA实现如下:
static public int totalNQueens(int n) {
if(n==1)
return 1;
int count = 0;
int[] queens = new int[n]; // queens are placed at (i, queens[i])
for (int i = 0; i < n; i++)
queens[i] = -1;
queens[0] = 0;
int k = 1;
while (k >=0) {
int j = findPosition(k, queens,n);
if (j ==-1) {
queens[k] = -1;
k--; // back track to the previous row
} else {
queens[k] = j;
if (k == n-1)
count++;
else {
k++;
}
}
}
return count;
}
public static int findPosition(int k, int[] queens,int n) {
int start = queens[k] == -1 ? 0 : queens[k] + 1;
for (int j = start; j < n; j++) {
if (isValid(k, j, queens,n))
return j;
}
return -1;
} public static boolean isValid(int k, int j, int queens[],int n) {
for (int i = 0; i < k; i++)
if (queens[i] == j)
return false;
for (int row = k - 1, column = j - 1; row >= 0 && column >= 0; row--, column--)
if (queens[row] == column)
return false;
for (int row = k - 1, column = j + 1; row >= 0 && column <= n-1; row--, column++)
if (queens[row] == column)
return false;
return true;
}