Java Implementation N Queen problem (backtracking method)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.