Hey guys, I working on solving 8 queens problem with out recursion and I came up with this
but somewhere in the program I missed something because I wouldn't get 40320 answer.
any idea?
public class EightQueens {
static int board[] = new int[8];
static int counter = 0;
public static boolean validIndex(int x) {
for (int i = 0; i < 8; i++) {
if (x != i) {
if (board[x] == board[i]){
return false;
}else if(board[x] == 1 || board[x] == 8 || x == 7 || x == 0){
for(int check = 1; check < 8; check++){
if(check == (i + 1) || check == (i - 1) ){
if(board[x] == board[i]){
if(i - 1 == check - 1){
if(i + 1 == check + 2){
return false;
}
}
}
}
}
}
}
}
return true;
}
public static boolean validBoard() {
for (int x = 0; x < 8; x++) {
if (!validIndex(x)) {
return false;
}
}
return true;
}
public static void solveQueen() {
for (int r1 = 1; r1 < 9; r1++) {
board[0] = r1;
for (int r2 = 1; r2 < 9; r2++) {
board[1] = r2;
for (int r3 = 1; r3 < 9; r3++) {
board[2] = r3;
for (int r4 = 1; r4 < 9; r4++) {
board[3] = r4;
for (int r5 = 1; r5 < 9; r5++) {
board[4] = r5;
for (int r6 = 1; r6 < 9; r6++) {
board[5] = r6;
for (int r7 = 1; r7 < 9; r7++) {
board[6] = r7;
for (int r8 = 1; r8 < 9; r8++) {
board[7] = r8;
if (validBoard()) {
counter++;
print();
}
}
}
}
}
}
}
}
}
}
public static void print() {
for (int row = 0; row < 8; row++) {
for (int x = 1; x < 9; x++) {
if (board[row] == x) {
System.out.print("Q");
} else {
System.out.print("B");
}
}
System.out.println("");
}
System.out.println("");
}
public static void main(String[] args) {
solveQueen();
System.out.println("The total number solutions for Eight Queens Problem is " + counter);
}
}
but somewhere in the program I missed something because I wouldn't get 40320 answer.
any idea?