public class Queens {.

Added on - 16 Sep 2019

  • 6

    Pages

  • 1261

    Words

  • 82

    Views

  • 0

    Downloads

Trusted by +2 million users,
1000+ happy students everyday
Showing pages 1 to 3 of 6 pages
public class Queens {// squares per row or per columnpublic static final int BOARD_SIZE = 8;//used to indicate empty squarepublic static final int EMPTY = 0;//used to indicate square contains a queenpublic static final int QUEEN = 1;private int board[][]; // chess boardpublic Queens() {// --------------------------------------------------// Constructor: Create an empty square board.// --------------------------------------------------board = new int[BOARD_SIZE][BOARD_SIZE];} // end constructorpublic void clearBoard(){// --------------------------------------------------// Clears the board.// Precondition: None.// Postcondition: Sets all squares to EMPTY// --------------------------------------------------// place your logic to implement this method here} // end clearBoardpublic 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 displayBoardpublic 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 columnwhile ( !queenPlaced && (row <= BOARD_SIZE) ) {// if square can be attackedif (isUnderAttack(row, column)) {++row; // consider next square in column} // end ifelse { // place queen and consider next columnsetQueen(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 columnremoveQueen(row, column);++row;} // end if} // end if} // end whilereturn queenPlaced;} // end if} // end placeQueens
desklib-logo
You’re reading a preview
Preview Documents

To View Complete Document

Click the button to download
Subscribe to our plans

Download This Document