public class Queen8 {
public static int num = 0; Total program Count
public static final int maxqueen = 8;//Queen number, and also the total number of checkerboard rows
public static int[] cols = new Int[maxqueen]; Defines the cols array, which represents the position of 8-column pieces
Public Queen8 () {
Core functions
Getarrangement (0);
System.out.print ("\ n");
System.out.println (maxqueen+ "Queen problem has" +num+ "kind of arrangement method. ");
}
public void getarrangement (int n) {
Iterates through all the illegal rows of the column and records with the rows array, illegal or 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 i=0;i<maxqueen;i++) {
Determine if the row is legal
if (Rows[i]) continue;
Sets the number of rows where the current column is a valid piece
Cols[n] = i;
When the current column is not the last column
if (n<maxqueen-1) {
Getarrangement (n+1);
}else{
Number of cumulative scenarios
num++;
Print Board information
Printchessboard ();
}
}
}
public void Printchessboard () {
System.out.print ("+num+", "take the Law \ n");
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.print ("\ n");
}
}
public static void Main (String args[]) {
Queen8 Queen = new Queen8 ();
}
}
Using Java to achieve eight queens