public class EightQueens {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 8;
enumerate(n);
}
public static void enumerate(int n){
int[] a = new int[n];
enumerate(a, 0);
}
public static void enumerate(int[] q, int k){
int n = q.length;
if(k == n)
printQueens(q);
else{
for(int i=0; i
if(isConsistent(q, k))
enumerate(q, k+1);
}
}
}
public static boolean isConsistent(int[] q, int n){
for(int i=0; i
return false;
if((q[i] - q[n]) == (n-i)) //same major diagonal (upper left entry to lower right entry)
return false;
if((q[n] - q[i]) == (n-i)) //same minor diagonal (upper right entry to lower left entry)
return false;
}
return true;
}
public static void printQueens(int[] q){
int n = q.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (q[i] == j)
System.out.print("Q ");
else
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
}
No comments:
Post a Comment