public class Nqueens {public static int num = 0;//total number of scenarios public static final int maxqueen = 5;//Queen number, and also the total number of board rows public St atic int[] cols = new Int[maxqueen]; Defines the cols array, which represents the public nqueens () {//core function for n-column pieces, starting with the No. 0 column 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 is rows[i]=trueboolean[] 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) ro Ws[cols[i] + d] = true;} for (int k = 0; k < Maxqueen; k++) {//Determine if the row is legal if (Rows[k]) continue;//set the current column the number of rows of the legal pawn cols[n] = k;//The current column is not the last column when the IF (N < MAXQUEEN-1) {getarrangement (n + 1);} else {//cumulative scheme number num++;//print checkerboard information Printchessboard ();}} public void Printchessboard () {System.out.println ("n" + 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");} Elsesystem.out.Print ("+");} System.out.println ();}} public static void Main (String args[]) {Nqueens Queen = new Nqueens ();}}
Reference documents
http://blog.csdn.net/zhong317/article/details/4586131
Http://zh.wikipedia.org/wiki/%E5%85%AB%E7%9A%87%E5%90%8E%E9%97%AE%E9%A2%98
Eight Queens question Java code