Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
八皇后問題:所有皇后所在行、列、斜線上不能有其他皇后出現。
用回溯法做,枚舉第一行皇后可以在的所有位置,根據所在位置推出第二個皇后所在位置,以此類推,當推到最後一個後,就count+1。在推導過程中,如果遇到非法位置,則回溯到上一層。所以只有到達最後一行的放置方法纔可以使count + 1。
用一維數組下標表示行,值表示列。
斜線判斷方法:行座標相減,列座標相減,如果相等或負相等(最好用兩個的絕對值, 比如出現[1,2]和[2,1])則在同一斜線上。
Source
public class Solution {
int count = 0;
public int totalNQueens(int n) {
if(n == 0) return 0;
int[] col = new int[n];
backtrack(n, 0, col);
return count;
}
public void backtrack(int n, int row, int[] col){
if(row == n){
count += 1;
return;
}
for(int i = 0; i < n; i++){
col[row] = i; //第row行放在i的位置上 枚舉i的位置
if(isValid(row, col))
backtrack(n, row + 1, col);
}
}
public boolean isValid(int row, int[] col){
for(int i = 0; i < row; i++){ //檢查已經放置的是否有效 注意end是row - 1
if(col[row] == col[i] || Math.abs(col[row] - col[i]) == row - i) //同一斜線上的點有的性質:絕對值列值相減==行值相減
return false;
}
return true;
}
}
Test
public static void main(String[] args){
int n = 4;
System.out.println(new Solution().totalNQueens(n));
}