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 the existence of a few queens, whether to meet the requirements, put 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.;//If 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));}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Implementation N Queen problem (backtracking method)