Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
N皇后问题是经典的NP问题,也是经典的回朔问题,思想就是放棋子,然后检查放的合不合理,如果不合理就撤回,然后继续放其他格子,直到合理位置。
至于如何检查,主要就是检查行列和对角线
public static boolean check(int row, int[] column) {
for (int i = 0; i < row; i++) {
if (column[i] == column[row]
|| Math.abs(column[row] - column[i]) == (row - i))
return false;
}
return true;
}
column[i]=j代表的意思是这个棋盘的第i行第j列被占用了
column[i]==column[row]代表的意思是第i行和第row行占用了同一列
column[row]-column[i]==row-i代表第i行和第row行在主对角线上
column[row]-column[i]==i-row代表第i行和第row行在副对角线上
然后每次就放,检查,回朔就可以了
完整代码如下
public static int totalNQueens(int n) {
if (n <= 0)
return 0;
int[] column = new int[n];
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(0);
helper(n, 0, column, result);
return result.get(0);
}
public static void helper(int n, int row, int[] column,
ArrayList<Integer> result) {
if (row == n) {
result.set(0, result.get(0) + 1);
return;
}
for (int i = 0; i < n; i++) {
column[row] = i;
if (check(row, column)) {
helper(n, row + 1, column, result);
}
}
}
public static boolean check(int row, int[] column) {
for (int i = 0; i < row; i++) {
if (column[i] == column[row]
|| Math.abs(column[row] - column[i]) == (row - i))
return false;
}
return true;
}
这里之所以不用恢复现场的原因是因为只用了一位数组记录没一行所被占的列,如果被占,那就跳过,就相当于是没有放,所以不存在被占用的情况