Write the complete Board.java class and the complete solveQueens.java class that
ID: 3676711 • Letter: W
Question
Write the complete Board.java class and the complete solveQueens.java class that will solve the “8 Queens” problem described in the slides provided in BrightSpace. The slides provide partial solution to the problem. Your program should print the solution in the following format. One solution is as follows:
Q - - - - - - - - - - - - - Q -
- - - - Q - - -
- - - - - - - Q
- Q - - - - - -
- - - Q - - - -
- - - - - Q - -
- - Q - - - - -
Write a method solveQueens that accepts a Board as a parameter and tries to place 8 queens on it safely. – Your method should stop exploring if it finds a solution.
// Searches for a solution to the 8 queens problem // with this board, reporting the first result found. public static void solveQueens(Board board) {
if (!explore(board, 1)) {
System.out.println("No solution found.");
} else {
System.out.println("One solution is as follows:"); System.out.println(board);
}
}
...
// Recursively searches for a solution to 8 queens on this
// board, starting with the given column, returning true if a
// solution is found and storing that solution in the board.
// PRE: queens have been safely placed in columns 1 to (col-1)
public static boolean explore(Board board, int col) {
if (col > board.size()) {
return true; // base case: all columns are placed
} else {
// recursive case: place a queen in this column
for (int row = 1; row <= board.size(); row++) {
if (board.isSafe(row, col)) {
board.place(row, col); // choose
if (explore(board, col + 1)) { // explore
return true; // solution found
} b.remove(row, col); // un-choose
}
}
return false; // no solution found
}
}
Its two seperate classes one of them is the client class other one is the class.
Explanation / Answer
public class Queens { /*************************************************************************** * Return true if queen placement q[n] does not conflict with * other queens q[0] through q[n-1] ***************************************************************************/ public static boolean isConsistent(int[] q, int n) { for (int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.