I am having a problem with the encoding problem of 8 queens. I coded a class to help me solve it, but for some reason I am doing something wrong. I understand what is going to happen.
In addition, we must use recursion to solve it, but I donβt know how to use the backtracking that I read about, so I just used it in methods that check if the position is legitimate.
My board String [] [] board = { { "O", "O"... etc. etc. with 8 rows and 8 columns. If I get something wrong conceptually or make a serious Java error, say this: D Thank you!
public void solve () { int Queens = NUM_Queens - 1; while (Queens > 0) { for (int col = 0; col < 8; col++) { int row = -1; boolean c = false; while (c = false && row < 8) { row ++; c = checkPos (row, col); } if (c == true) { board[row][col] = "Q"; Queens--; } else System.out.println("Error"); } } printBoard (); } // printing the board public void printBoard () { String ret = ""; for (int i = 0; i < 8; i++) { for (int a = 0; a < 8; a++) ret += (board[i][a] + ", "); ret += ("\n"); } System.out.print (ret); } // checking if a position is a legitimate location to put a Queen public boolean checkPos (int y, int x) { boolean r = true, d = true, u = true, co = true; r = checkPosR (y, 0); co = checkPosC (0, x); int col = x; int row = y; while (row != 0 && col != 0 ) { //setting up to check diagonally downwards row--; col--; } d = checkPosDD (row, col); col = x; row = y; while (row != 7 && col != 0 ) { //setting up to check diagonally upwards row++; col--; } d = checkPosDU (row, col); if (r = true && d = true && u = true && co = true) return true; else return false; } // checking the row public boolean checkPosR (int y, int x) { if (board[y][x].contentEquals("Q")) return false; else if (board[y][x].contentEquals("O") && x == 7) return true; else //if (board[y][x].contentEquals("O")) return checkPosR (y, x+1); } // checking the column public boolean checkPosC (int y, int x) { if (board[y][x].contentEquals("Q")) return false; else if (board[y][x].contentEquals("O") && y == 7) return true; else //if (board[y][x].contentEquals("O")) return checkPosR (y+1, x); } // checking the diagonals from top left to bottom right public boolean checkPosDD (int y, int x) { if (board[y][x].contentEquals("Q")) return false; else if (board[y][x].contentEquals("O") && (x == 7 || y == 7)) return true; else //if (board[y][x].contentEquals("O")) return checkPosR (y+1, x+1); } // checking the diagonals from bottom left to up right public boolean checkPosDU (int y, int x) { if (board[y][x].contentEquals("Q")) return false; else if (board[y][x].contentEquals("O") && (x == 7 || y == 0)) return true; else //if (board[y][x].contentEquals("O")) return checkPosR (y-1, x+1); } }
source share