Now, instead outputting board configurations, return the total number of distinct solutions.
public class Solution { private int num; // Number of lines of board private int nSolution; // Number of solutions private int[] x; // Position of queens public int totalNQueens(int n) { // Backtracking problem // Construct a (n+1) level tree: The ith (i = 0,1,...,n) level has n^i nodes // x[i] also represents there is a queen on the ith row x[i]th column num = n; nSolution = 0; x = new int[n]; backTrack(0); return nSolution; } private void backTrack(int cnt) { if (cnt == num) // Passed the last row and get a possible solution nSolution++; else { for (int j = 0; j < num; j++) { x[cnt] = j; // Test if x[cnt] can be positioned if (place(cnt)) backTrack(cnt+1); } } } // Constrained rule: The queens can be be put in the same row, column or line with slope (-1 or +1) private boolean place(int j) { for (int i = 0; i < j; i++) if (x[i]==x[j] || Math.abs(i-j)==Math.abs(x[i]-x[j])) return false; return true; } }
No comments:
Post a Comment