Link:http://oj.leetcode.com/problems/n-queens-ii/
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
1 public class Solution { 2 public int num = 0; 3 public int totalNQueens(int n) { 4 if (n < 1) 5 return 0; 6 num = 0; 7 int[] queens = new int[n + 1]; 8 for (int i = 1; i <= n; i++) { 9 queens[1] = i; 10 dfs(2, n, queens); 11 } 12 return num; 13 } 14 public void dfs(int col, int size, int[] queens) { 15 if (col > size) { 16 num++; 17 return; 18 } 19 // here i means row number; 20 for (int i = 1; i <= size; i++) { 21 if (isValid(i, col, queens)) { 22 queens[col] = i; 23 dfs(col + 1, size, queens); 24 queens[col] = 0; 25 } 26 } 27 } 28 29 public boolean isValid(int row, int col, int[] queens) { 30 for (int i = 1; i < col; i++) { 31 // queens should not be in the same row, 32 // queens should not be placed in the duijiaoxian... 33 // which means |x1-x2|==|y1-y2| 34 if (queens[i] != 0 35 && (queens[i] == row || (Math.abs(i - col) == Math 36 .abs(queens[i] - row)))) 37 return false; 38 } 39 return true; 40 } 41 }