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