Package com.leetcode;/** * Follow up for n-queens problem. Now, instead outputting board configurations and return the total number of distinct solutions. * @author Zealot * @date July 23, 2015 PM 6:14:49 */public class Nqueensii {int[] x;//current solution int n;//Queen number int sum = 0;//currently found The number of possible scenarios for public int totalnqueens (int n) {n = n;x = new Int[n+1];backtrace (1); return sum;} /** * Col Line this point, X[col] column this point. With several queens that already existed. Whether it meets the requirements, put it in this position, * @param col * @return */private boolean place (int col) {for (int i = 1; i < col; i++) {if (Math.Abs (Col- i) ==math.abs (X[col]-x[i]) | | X[col]==x[i]) {return false;}} return true;} private void BackTrace (int t) {if (t>n) {sum++;} else {//T line. Traverse all nodes for (int j = 1; J <= N; j + +) {x[t] = j;//Assuming that the J node can drop the Queen if (place (t)) {//Then drop a backtrace (t+1);}}} public static void Main (string[] args) {nqueensii n = new nqueensii (); System.out.println (N.totalnqueens (8));}}
Java Implementation N Queen problem (backtracking method)