# Solving the Eight Queens Problem

6 Pages1261 Words107 Views
|
|
|
public class Queens { // squares per row or per column public static final int BOARD_SIZE = 8; //used to indicate empty square public static final int EMPTY = 0; //used to indicate square contains a queen public static final int QUEEN = 1; private int board[][]; // chess board public Queens() { // -------------------------------------------------- // Constructor: Create an empty square board. // -------------------------------------------------- board = new int[BOARD_SIZE][BOARD_SIZE]; } // end constructor public void clearBoard(){ // -------------------------------------------------- // Clears the board. // Precondition: None. // Postcondition: Sets all squares to EMPTY // -------------------------------------------------- // place your logic to implement this method here } // end clearBoard public void displayBoard(){ // --------------------------------------------------
// Displays the board. // Precondition: None. // Postcondition: Board is written to standartd // output; zero is an EMPTY square, one is a square // containing a queen (QUEEN) // -------------------------------------------------- for (int i=0; i<BOARD_SIZE; i++) { for (int j=0; j<BOARD_SIZE; j++) {// place your logic to implement this method here // that prints a single row of the chess board // to the console window (i.e., standard output) } System.out.print("\n"); // this newline prints after a row // of the chess board has been printed } } // end displayBoard public boolean placeQueens(int column) { // -------------------------------------------------- // Place queens in columns of the board beginning // at the column specified. // Precondition: Queens are placed correctly in // columns 1 thro coulumn-1. // Postcondition: If a solution is found, each // column of the board contains one queen and method // returns true; otherwise retruns false (no // solution existis for a queen anywhere in column // specified).
// --------------------------------------------------if (column > BOARD_SIZE) { return true; // base case}else { boolean queenPlaced = false; int row = 1; // number of square in column while ( !queenPlaced && (row <= BOARD_SIZE) ) { // if square can be attacked if (isUnderAttack(row, column)) { ++row; // consider next square in column } // end if else { // place queen and consider next column setQueen(row, column); queenPlaced = placeQueens(column+1); // if no queen is possible in the next column, if (!queenPlaced) { // backtrack: remove queen placed earliers // and try next square in column removeQueen(row, column); ++row; } // end if } // end if } // end while return queenPlaced;} // end if } // end placeQueens

## End of preview

Want to access all the pages? Upload your documents or become a member.

### Support

#### +1 306 205-2269

Chat with our experts. we are online and ready to help.