I'm creating an N Queens problem solver with Backtracking. The twist however is that the first queen is placed by the user and then the backtracking is run to process the other 7 queens. My program functions to fulfill this task and the backtracking is functional however I can only place the queen on the first left column as the parameter the function takes is the column to start the backtracking procedure on.
Board class
public boolean solveQueen(int col) {
if (col >= board.length) {
printBoard();
System.out.println("queen");
return true;
}
for (int i = 0; i < board.length; i++)
if (notUnderAttack(i, col)) {
placeQ(i, col);
solveQueen(col + 1);
removeQ(i, col);
}
return false;
}
Main class
queen.placeQ(0, 2);
queen.solveQueen(3);
queen.printBoard();
To solve this I've tried wrapping around the first queen and starting the backtracking a column after the initial placement but the problem here is that whilst it places the queens at 3,4,5,6,7 column and the preplaced queen is at the 2nd column the first column has no queens. I'm not quite sure how to add the queen in the first column. I've tried using modulo but I'm not sure if I've implemented that correctly so I removed it.
public boolean notUnderAttack(int row, int col) {
if ((rowCheck(row) == false) || (colCheck(col) == false) || (diagonalCheck(row, col) == false)) {
return false;
}
return true;
}
You can either store the column of the initial queen and then skip that column solveQueen
. or. create a method that check for a queen in the column already and skips based on that. And then always just call solveQueen(1)
The first solution is good (more efficient) if you only ever want to place the 1st queen. Second is better if you may expand this to handle multiple placed initial queens.