Eight Queens Java algorithm

Source: Internet
Author: User

public class Nqueens {public static int num = 0;//total number of scenarios public static final int maxqueen = 5;//Queen number, and the total number of checkerboard rows Publi C static int[] cols = new Int[maxqueen]; Defines the cols array, which represents the position of the N-column pieces

Public Nqueens () {//core function, starting from column No. 0 getarrangement (0); System.out.println (Maxqueen + Queen problem has + num + kind of placement method.  ); }

public void getarrangement (int n) {//iterates through all illegal rows of the column and records with rows array, illegal i.e. rows[i]=true boolean[] rows = new Boolean[maxqueen];  for (int i = 0; i < n; i++) {Rows[cols[i]] = true;  int d = n-i;  if (Cols[i]-d >= 0) Rows[cols[i]-d] = true; if (Cols[i] + D <= MAXQUEEN-1) Rows[cols[i] + d] = true;

}

for (int k = 0; k < Maxqueen; k++) {//Determine if the line is legal if (rows[k]) continue;  Sets the number of rows in the current column for a valid piece cols[n] = k;  If the current column is not the last column (n < MAXQUEEN-1) {getarrangement (n + 1);  } else {//cumulative scheme number num++;  Print Board information Printchessboard (); }  }  }

public void Printchessboard () {System.out.println (first + num + seed walk); for (int i = 0; i < Maxqueen; i++) {for (int j = 0; J < Maxqueen;  J + +) {if (i = = Cols[j]) {System.out.print (0);  } else System.out.print (+);  } System.out.println (); }

}

public static void Main (String args[]) {Nqueens Queen = new Nqueens (); } }

Eight Queens Java algorithm

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.