There are 92 solutions for 8 Queens.
The solution uses a 1D array and does not use recursion.
public class EightQueen {
private static final int N = 8;
//queens[2]=3, means the queen on row 2 is placed on column 3
private static int[] queens = new int[N];
private static int index = 0;
private static int counter = 0;
public static void placeQueens(){
int previousColumn = -1;
boolean noMoreSolutions = false;
while (!noMoreSolutions){
while (index < N){
int col = getColumnForNextRow(previousColumn);
if (col != -1){
queens[index++] = col;
previousColumn = -1;
}else if (index > 0){
previousColumn = queens[--index];
}else{
noMoreSolutions = true;
System.out.println("No More Solutions");
break;
}
}
if (!noMoreSolutions){
print();
System.out.println("Solution #"+ ++counter);
//Let's find another solution
previousColumn = queens[--index];
}
}
}
private static int getColumnForNextRow(int previousColumn) {
int startCol = previousColumn + 1;
for (int j=startCol; j < N; j++){
if (!canAttackExistingQueens(j)){
return j;
}
}
return -1;
}
private static boolean canAttackExistingQueens(int col) {
for (int i=0; i<index; i++){
if (canAttackQueen(index, col, i, queens[i])){
return true;
}
}
return false;
}
private static boolean canAttackQueen(int row1, int col1, int row2, int col2) {
return sameCol(col1, col2) || sameDiagonal(row1, col1, row2, col2);
}
private static boolean sameCol(int col1, int col2) {
return col1 == col2;
}
private static boolean sameDiagonal(int row1, int col1, int row2, int col2) {
return col1 - col2 == row1 - row2 || col1 - col2 == row2 - row1;
}
private static void print(){
for (int i=0; i<N; i++){
for (int j=0; j<N; j++){
if (queens[i] == j){
System.out.print("Q ");
}else{
System.out.print("* ");
}
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
placeQueens();
}
}
No comments:
Post a Comment