Question

================Data Structures C++=============== – Implement the Eight Queens Problem This is a...

================Data Structures C++===============

– Implement the Eight Queens Problem

This is an object oriented program. This is #1 on page 187 of your book with ONE difference, I’m requiring you add a client program to test your code (a main). If you have the old book the question says “Complete the Queen and Board class for the Eight Queens problem.”

On page 179 of your book is a function placeQueens that solves the Eight Queens problem.

On page 180 of your book are some suggestions to implementing two ADTs to solve the problem in C++. I want you to follow their suggestions to implement the solution.

  1. First create a Board class data type. This class data type should represent the chess board (you can use any implementation you want, a two dimensional array (however this may waste space but not if you’re displaying in my opinion), a vector (it could represent only the board places occupied by queens), an array of vectors etc – there is more than one right way!). The board should keep track of the Queens currently placed on it and contain operations/methods (such as placeQueens and displayBoard) to solve the problem and display a solution. You can add other methods as you need them. Note the board will need to contain a Queen (or perhaps an array or vector of queens) – I haven’t done this problem yet but I immediately thought composition might be needed.
  2. Next create a Queen data type. A queen instance should be able to keep track of its current position (row and column) and be able to move to the next row. Again you can add other methods as you see fit.
  3. Add a client program to test your code:
    • This program should place the first queen anywhere on the board and then call placeQueens to see if a solution can be reached. If the solution can be reached the program should display the board with the queens properly placed.
    • The header fi le for the class Board from the book example
      /** @file Board.h */
      #ifndef _BOARD
      #define _BOARD
      #include "Queen.h"
      #include <vector>
      #include <cassert>#include <iostream>
      using namespace std;
      static const int BOARD_SIZE = 8;
      class Board
      {
      private :
      vector<Queen*> queens; // Array of pointers to queens on the board
      /** Sees whether a queen exists in position (inRow, inCol). */
      bool isQueen( int inRow, int inCol) const;
      /** Attempts to place queens on board, starting with the designated queen. */
      const placeQueens(Queen* queenPtr);
      /** Removes the last queen from the board, but does not deallocate it. */
      void removeQueen();
      /** Places a queen on the board. */
      void setQueen( const Queen* queenPtr);
      public:
      /** Supplies the Queen class with a pointer to the board. */
      Board();
      /** Clears the board and removes pointer from queens. */
      ~Board();
      /** Clears board. */
      void clear();
      /** Displays board. */
      void display() const;
      /** Initiates the Eight Queens problem. */
      void doEightQueens();
      /** @return The number of queens on the board. */
      int getNumQueens() const;
      /** @return A pointer to the queen at the designated index. */
      const Queen* getQueen( int index) const;
      }; // end Board
      #endif
      LISTING 5-2 The class Queen
      class Board; // Forward declaration of Board class
      /** The Queen class. */
      class Queen
      {
      public:
      /** Places a queen in upper-left corner of board. */
      Queen();/** Places a queen in supplied location. */
      Queen( int inRow, int inCol);
      /** @return Column number. */
      int getCol() const;
      /** @return Row number. */
      int getRow() const;
      /** Moves queen to next row. */
      void nextRow();
      /** Sees whether the queen is under attack by another queen.
      @return True if another queen is in the same row or the same
      diagonal; otherwise, returns false. */
      bool isUnderAttack() const;
      /** Saves a pointer to the board for all queens. */
      static void setBoard( const Board* bPtr);
      private:
      int row; // Row (or prospective row) of queen if it is on the board
      int col; // Column (or prospective column) of queen if it is on
      // the board
      // All queens share the same board
      static const Board* boardPtr;
      }; // end Queen
      An implementation of placeQueens follows:
      bool Board::placeQueens(Queen* queenPtr)
      {
      // Base case: Try to place a queen in a nonexistent column.
      if (queenPtr->getCol() >= BOARD_SIZE)
      {
      delete queenPtr;
      return true;
      } // end if
      bool isQueenPlaced = false;
      while (!isQueenPlaced && queenPtr->getRow() < BOARD_SIZE)
      {
      // If the queen can be attacked, try moving it
      // to the next row in the current column
      if (queenPtr->isUnderAttack())
      queenPtr->nextRow();
      else
      {
      // Put this queen on the board and try putting a
      // new queen in the first row of the next column
      setQueen(queenPtr);
      Queen* newQueenPtr = new Queen(0, queenPtr->getCol() + 1);
      isQueenPlaced = placeQueens(newQueenPtr);// If it wasn't possible to put the new queen in the next column,
      // backtrack by deleting the new queen and moving the last
      // queen placed down one row
      if (!isQueenPlaced)
      {
      delete newQueenPtr;
      removeQueen();
      queenPtr->nextRow();
      } // end if
      } // end if
      } // end while
      return isQueenPlaced;
      } // end placeQueens
0 0
Add a comment Improve this question Transcribed image text
Answer #1


Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)

//main.cpp
#include <iostream>
#include <vector>
#include "Queen.h"
#include "Board.h"
#include "Queen.cpp"
#include "Board.cpp"
using namespace std;
#include <iostream>

int main() {
    Board board;
    for (int row = 0; row < 8; row++) {
        Queen queen(row, 0);
        queen.setBoard(&board);
        board.doEightQueens(queen);
        board.display();
        board.clear();
        cout << endl;
    }
    system("PAUSE");
    return 0;
}

-----------------------------------------------------------------------------------------------------------
//Queen.cpp
#include "Queen.h"
#include "Board.h"
#include <iostream>
using namespace std;

const Board* Queen::boardPtr;

Queen::Queen() : row(0), col(0) {
}

Queen::Queen(int inRow, int inCol) : row(inRow), col(inCol) {

}

Queen::~Queen() {

}

int Queen::getCol() const {
    return col;
}

int Queen::getRow() const {
    return row;
}
void Queen::nextRow() {
    ++row;
}

bool Queen::isUnderAttack() const {
    for (int i = 0; i < boardPtr->getNumQueens(); i++) {
        const Queen* q = boardPtr->getQueen(i);
        if (q->getCol() == col || q->getRow() == row || q->getRow()-q->getCol() == row-col || q->getRow()+q->getCol() == row+col)
            return true;
    }
    return false;
}

void Queen::setBoard(const Board* bPtr) {
    boardPtr = bPtr;
}


-----------------------------------------------------------------------------------------------------------
//Queen.h
#ifndef QUEEN_H
#define QUEEN_H

class Board; class Queen {
public:
    Queen();
    ~Queen();
    Queen(int inRow, int inCol);
    int getCol() const;
    int getRow() const;
    void nextRow();
    static void setBoard(const Board* bPtr);
    bool isUnderAttack() const;
private:
    int row;
    int col;
    static const Board* boardPtr;


};
#endif
-----------------------------------------------------------------------------------------------------------
//Board.cpp
#include <iostream>
#include <vector>
#include "Board.h"
using namespace std;

Board::Board() {
    Queen::setBoard(this);
}

Board::~Board() {
    clear();
}

bool Board::placeQueens(Queen* queenPtr) {
    if (queenPtr->getCol() >= BOARD_SIZE) {
        delete queenPtr;
        return true;
    }

    bool isQueenPlaced = false;

    while (!isQueenPlaced && queenPtr->getRow()<BOARD_SIZE) {

        if (queenPtr->isUnderAttack()) {
            queenPtr->nextRow();
        }
        else {
            setQueen(queenPtr);
            Queen* newQueenPtr = new Queen(0, queenPtr->getCol() + 1);
            isQueenPlaced = placeQueens(newQueenPtr);
            if (!isQueenPlaced) {
                delete newQueenPtr;
                removeQueen();
                queenPtr->nextRow();
            }
        }
    }
    return isQueenPlaced;
}

void Board::doEightQueens(Queen q) {
    placeQueens(new Queen(q.getRow(),q.getCol()));
}

void Board::clear() {
    for (int i = getNumQueens(); i > getNumQueens() ;++i) {
        delete (queens[i]);
    }
    queens.clear();
}

void Board::removeQueen() {
    if (queens.size() != 0)
        queens.pop_back();
}

bool Board::isQueen(int row, int col) const {
    bool isOnBoard = false;
    for (int i = 0; i < (int)queens.size(); i++) {
        if (queens[i]->getRow() == row && queens[i]->getCol() == col) {
            isOnBoard = true;
        }
    }
    return isOnBoard;
}
void Board::setQueen(Queen* queenPtr) {
    queens.push_back(queenPtr);
}


void Board::display() const {
    cout << " ";
    for (int rowNum = 0; rowNum < BOARD_SIZE; rowNum++)
        cout << rowNum << " ";
    cout << endl;
    for (int row = 0; row < BOARD_SIZE; row++) {
        cout << row << " ";
        for (int col = 0; col < BOARD_SIZE; col++) {
            if (isQueen(row, col)) {
                cout << "Q ";
            }
            else cout << "+ ";
        } cout << endl;
    }

}

int Board::getNumQueens() const {
    return queens.size();
}

const Queen* Board::getQueen(int index) const {
    return queens[index];
}

-----------------------------------------------------------------------------------------------------------

//Board.h
#ifndef _BOARD
#define _BOARD
#include "Queen.h"
#include <vector>
#include <cassert>
#include <iostream>
using namespace std;

static const int BOARD_SIZE = 8;
class Board {
private:
    vector<Queen*> queens;
    bool isQueen(int inRow, int inCol) const ;
    bool placeQueens(Queen* queenPtr);
    void removeQueen();
    void setQueen( Queen* queenPtr);

public:
    Board();
    ~Board();
    void clear();
    void display() const;
    void doEightQueens(Queen q);
    int getNumQueens() const;
    const Queen* getQueen(int index) const;
};
#endif
/CLionProjects/Eight m] - main.cpp main.cpp *증 *-Δ cMakel.ists.txt main.cppQueenepp Queen.h.cpp Board.h Project ▼ /Users/swap

Add a comment
Know the answer?
Add Answer to:
================Data Structures C++=============== – Implement the Eight Queens Problem This is a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Complete the program that solves the Eight Queens problem. The program’s output should look similar to:...

    Complete the program that solves the Eight Queens problem. The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| Use the Queens class given. In your implementation of the Queens class, complete the body of all methods marked as “To be implemented in Programming Problem 1.” Do not change any of the global variable declarations, constructor or placeQueens methods. Here is what I have so far with notes of what is needed. public class Queens...

  • Please help i need a C++ version of this code and keep getting java versions. Please...

    Please help i need a C++ version of this code and keep getting java versions. Please C++ only Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide...

  • in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the...

    in c++ Purpose: This lab will give you experience harnessing an existing backtracking algorithm for the eight queens problem, and seeing its results displayed on your console window (that is, the location of standard output). Lab A mostly complete version of the eight queens problem has been provided for you to download. This version has the class Queens nearly completed. You are to provide missing logic for the class Queens that will enable it to create a two-dimensional array that...

  • Complete the program that solves the Eight Queens problem in java only please (pages 318 through...

    Complete the program that solves the Eight Queens problem in java only please (pages 318 through 320). The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| PlaceQueens(in currColumn:integer) //places queens in columns numbered currColumn through 8 If (currColumn>8){ The problem is solved } Else { While(unconsidered squares exist in curr column and the problem is unsolved ){ Determine the next square in column currColumn that is not under attack by a queen in an...

  • please explain/ comment 3. Eight Queens Write a program that places eight queens on a chessboard...

    please explain/ comment 3. Eight Queens Write a program that places eight queens on a chessboard (8 x 8 board) such that no queen is "attacking" another. Queens in chess can move vertically, horizontally, or diagonally. How you solve this problem is entirely up to you. You may choose to write a recursive program or an iterative (i.e., non-recursive) program. You will not be penalized/rewarded for choosing one method or another. Do what is easiest for you. 3.1. Output Below...

  • Write a program to place eight queens on an 8 x 8 chessboard in such a...

    Write a program to place eight queens on an 8 x 8 chessboard in such a way that one queen is to be in each row. A program will use 2 DIMENIONAL array x[r][c] to do this configuration. If x[r] has value c, then in row r there is a queen in column c. Write a program that asks a user to enter the columns that contain queens in the 8 rows. The program then places the queens in these...

  • I have a question about C++. I have to code the 8 queens puzzle without using...

    I have a question about C++. I have to code the 8 queens puzzle without using any recursive methods. Every time the program runs, it will randomly place 8 queens throughout the board. I got that working, but the issue is the board is suppose to be filled with asterisks and the queens are suppose to be represented with a Q. I have put zeros instead of asterisks and ones instead of Qs, i tried to fix it but it...

  • 110Marks Question No. 4 Eight queens problem: place 8 queens on a chess board so that no two queens attack each other. -state: locations of 0 to 8 queens (with no two queens attacking each other) goa...

    110Marks Question No. 4 Eight queens problem: place 8 queens on a chess board so that no two queens attack each other. -state: locations of 0 to 8 queens (with no two queens attacking each other) goal test: 8 queens placed on the board (with none attacked) operator: place a queen in the left-most empty column such that it is not attacked by any other queen (and does not attack any other queen) path cost: 0 Depth first search: i....

  • Can you explain how this code for the 8 Queens Problem works? It's in C++ In case you dont know w...

    Can you explain how this code for the 8 Queens Problem works? It's in C++ In case you dont know what the 8 Queens problem is, "The eight queens puzzle is the problem of placing eightchess queens on an 8×8 chessboard so that no two queensthreaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal." This is the code: #include <iostream> #include <cmath> using namespace std; bool ok(int q[], int c) {     ...

  • PLEASE COMPLETE IN C++ LANGUAGE Location row : int = -1 col : int = -1...

    PLEASE COMPLETE IN C++ LANGUAGE Location row : int = -1 col : int = -1 setLocation(row : int, col : int) getRow(): int getColl): int isEmpty(): bool Details Write all the code necessary to implement the Location class as shown in the UML Class Diagram to the right. Do this in a project named snake (we'll continue adding files to this project as the term progresses). Your class definition and implementation should be in separate files. When complete, you...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT