Question

I NEED HELP IN MAZE PROBLEM. Re-write the following program using classes. The design is up...

I NEED HELP IN MAZE PROBLEM.

Re-write the following program using classes. The design is up to you, but at a minimum, you should have a Maze class with appropriate constructors and methods. You can add additional classes you may deem necessary.

// This program fills in a maze with random positions and then runs the solver to solve it.

// The moves are saved in two arrays, which store the X/Y coordinates we are moving to.

// They are output in main in forward order.

//

#include <iostream>

#include <ctime>

#include <cstdlib>

using namespace std;

// ************ Width and Height changed to 20x20 ********************

const int WIDTH = 20;

const int HEIGHT = 20;

// Function prototypes

void printMaze(char maze[][WIDTH], int curx, int cury);

bool validMove(char maze[][WIDTH], bool visited[][WIDTH],

   int newX, int newY);

bool move(char maze[][WIDTH], bool visited[][WIDTH],

int &curX, int &curY, int newX, int newY);

// *** search has new parameters to remember the coordinates of the solution we find

bool search(char maze[][WIDTH], bool visited[][WIDTH], int x, int y,

int solutionX[], int solutionY[], int &numEntries);

// *** New function, see below

void addToArrays(int x[], int y[], int &numEntries, int xVal, int yVal);

// This new function adds two numbers to the arrays and increments the count of how many

// numbers have been added. It assumes the arrays have been created big enough to not

// have overflow. It is used to remember the coordinates of our solution.

void addToArrays(int x[], int y[], int &numEntries, int xVal, int yVal)

{

   x[numEntries] = xVal;

   y[numEntries] = yVal;

   numEntries++;

}

// Return true or false if moving to the specified coordinate is valid

// Return false if we have been to this cell already

bool validMove(char maze[][WIDTH], bool visited[][WIDTH],

   int newX, int newY)

{

// Check for going off the maze edges

if (newX < 0 || newX >= WIDTH)

return false;

if (newY < 0 || newY >= HEIGHT)

return false;

// Check if target is a wall

if (maze[newY][newX]=='X')

return false;

// Check if visited

if (visited[newY][newX])

return false;

return true;

}

// Make the move on the maze to move to a new coordinate

// I passed curX and curY by reference so they are changed to

// the new coordinates. Here we assume the move coordinates are valid.

// This returns true if we move onto the exit, false otherwise.

// Also update the visited array.

bool move(char maze[][WIDTH], bool visited[][WIDTH],

int &curX, int &curY, int newX, int newY)

{

bool foundExit = false;

if (maze[newY][newX]=='E') // Check for exit

foundExit = true;

curX = newX; // Update location

curY = newY;

visited[curY][curX] = true;

return foundExit;

}

// Display the maze in ASCII

void printMaze(char maze[][WIDTH], int curx, int cury)

{

for (int y=0; y < HEIGHT;y++)

{

for (int x=0; x < WIDTH; x++)

{

if ((x==curx) && (y==cury))

cout << "@";

else

cout << maze[y][x];

}

cout << endl;

}

}

// Recursively search from x,y until we find the exit

bool search(char maze[][WIDTH], bool visited[][WIDTH],

int x, int y,

int solutionX[], int solutionY[], int &numEntries)

{

   bool foundExit;

   if (maze[y][x]=='E')

return true;

   visited[y][x]=true;

   if (validMove(maze,visited,x,y-1))

foundExit = search(maze,visited,x,y-1,solutionX,solutionY,numEntries);

   if (!foundExit && (validMove(maze,visited,x,y+1)))

foundExit = search(maze,visited,x,y+1,solutionX,solutionY,numEntries);

   if (!foundExit && (validMove(maze,visited,x-1,y)))

foundExit = search(maze,visited,x-1,y,solutionX,solutionY,numEntries);

   if (!foundExit && (validMove(maze,visited,x+1,y)))

foundExit = search(maze,visited,x+1,y,solutionX,solutionY,numEntries);

   if (foundExit)

   {

// Remember coordinates we found the exit in the solution arrays

addToArrays(solutionX, solutionY, numEntries, x, y);

return true;

   }

   return false;

}

int main()

{

char maze[HEIGHT][WIDTH];

bool visited[HEIGHT][WIDTH];

// Seed random number generator with clock time

srand(time(NULL));

/****************

Programmatically fill out the maze with ***'s on the borders and spaces in the middle

****************/

// All blank

for (int x = 0; x < WIDTH; x++)

for (int y = 0; y < HEIGHT; y++)

maze[y][x] = ' ';

// Borders with X

for (int x = 0; x < WIDTH; x++)

{

maze[0][x] = 'X';

maze[HEIGHT-1][x] = 'X';

}

for (int y = 0; y < HEIGHT; y++)

{

maze[y][0] = 'X';

maze[y][WIDTH-1] = 'X';

}

// ***** Randomly fill in 25% of the middle

int numCells = static_cast<int>((HEIGHT-2)*(WIDTH-2)*0.25);

int count = 0;

while (count < numCells)

{

int x = (rand() % (WIDTH-2)) +1;

int y = (rand() % (HEIGHT-2)) +1;

if (maze[y][x]==' ')

{

maze[y][x]='X';

count++;

}

}

// ***** Pick a random start and end that is not a wall *****

int x = (rand() % (WIDTH-2)) +1;

int y = (rand() % (HEIGHT-2)) +1;

while (maze[y][x]=='X')

{

   x = (rand() % (WIDTH-2)) +1;

   y = (rand() % (HEIGHT-2)) +1;

}

// At this point, (x,y) contains our start position

// ***** Pick a random end position that is not a wall *******

int exitX = (rand() % (WIDTH-2)) +1;

int exitY = (rand() % (HEIGHT-2)) +1;

while (maze[exitY][exitX]=='X')

{

   exitX = (rand() % (WIDTH-2)) +1;

   exitY = (rand() % (HEIGHT-2)) +1;

}

maze[exitY][exitX]='E';

// Initialize visited locations to false

for (int x = 0; x < WIDTH; x++)

for (int y = 0; y < HEIGHT; y++)

visited[y][x] = false;

visited[y][x] = true;

// Here I created arrays to store the x/y coordinates for the path of our solution.

// The array is of size [HEIGHT-2]*[WIDTH-2] since we'll never exceed that size.

// I also made a variable to count how many entries we make..

// It would probably be more convenient to make a class to store this data rather than

// have two separate arrays!

int solutionX[(HEIGHT-2)*(WIDTH-2)], solutionY[(HEIGHT-2)*(WIDTH-2)];

int numPoints = 0;

bool found = search(maze,visited,x,y,solutionX,solutionY,numPoints);

if (!found)

cout << "No solution found.";

else

{

cout << "Solution found! Here is the path from the start." << endl;

for (int i = numPoints-1; i >= 0; i--)

{

printMaze(maze, solutionX[i], solutionY[i]);

cout << endl;

}

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//I tried to keep it simple! Please ask for clarifications if any and kindly give feedback.

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

// ************ Width and Height changed to 20x20 ********************
const int WIDTH = 20;
const int HEIGHT = 20;

class Maze
{
   private:
       char maze[HEIGHT][WIDTH];
       bool visited[HEIGHT][WIDTH];
       int numPoints, startX, startY, solutionX[(HEIGHT-2)*(WIDTH-2)], solutionY[(HEIGHT-2)*(WIDTH-2)];
       void printMaze(int curx, int cury);
       bool validMove(int newX, int newY);
       bool move(int &curX, int &curY, int newX, int newY);
       // *** search has new parameters to remember the coordinates of the solution we find
       bool search(int x, int y);
       // *** New function, see below
       void addToArrays(int xVal, int yVal);
  
   public:
  
       Maze()
       {
           // Seed random number generator with clock time
           srand(time(NULL));
           numPoints=0;
           /****************
           Programmatically fill out the maze with ***'s on the borders and spaces in the middle
           ****************/
           // All blank
           for (int x = 0; x < WIDTH; x++)
           for (int y = 0; y < HEIGHT; y++)
               maze[y][x] = ' ';
           // Borders with X
           for (int x = 0; x < WIDTH; x++)
           {
               maze[0][x] = 'X';
               maze[HEIGHT-1][x] = 'X';
           }
           for (int y = 0; y < HEIGHT; y++)
           {
               maze[y][0] = 'X';
               maze[y][WIDTH-1] = 'X';
           }
       }
  
       void randomFill()
       {
           // ***** Randomly fill in 25% of the middle
           int numCells = static_cast<int>((HEIGHT-2)*(WIDTH-2)*0.25);
           int count = 0;
           while (count < numCells)
           {
           int x = (rand() % (WIDTH-2)) +1;
           int y = (rand() % (HEIGHT-2)) +1;
           if (maze[y][x]==' ')
           {
           maze[y][x]='X';
           count++;
           }
           }
           // ***** Pick a random start and end that is not a wall *****
           int x = (rand() % (WIDTH-2)) +1;
           int y = (rand() % (HEIGHT-2)) +1;
           while (maze[y][x]=='X')
           {
               x = (rand() % (WIDTH-2)) +1;
               y = (rand() % (HEIGHT-2)) +1;
           }
           // At this point, (x,y) contains our start position
           startX = x;
           startY = y;
           visited[y][x] = true;
      
           // ***** Pick a random end position that is not a wall *******
           int exitX = (rand() % (WIDTH-2)) +1;
           int exitY = (rand() % (HEIGHT-2)) +1;
           while (maze[exitY][exitX]=='X')
           {
               exitX = (rand() % (WIDTH-2)) +1;
               exitY = (rand() % (HEIGHT-2)) +1;
           }
           maze[exitY][exitX]='E';
           // Initialize visited locations to false
           for (int x = 0; x < WIDTH; x++)
           for (int y = 0; y < HEIGHT; y++)
               visited[y][x] = false;
       }
  
       void printPath()
       {
           bool found = search(startX, startY);
           if (!found)
               cout << "No solution found.";
           else
           {
               cout << "Solution found! Here is the path from the start." << endl;
               for (int i = numPoints-1; i >= 0; i--)
               {
                   printMaze(solutionX[i], solutionY[i]);
                   cout << endl;
               }
           }
       }
};

// This new function adds two numbers to the arrays and increments the count of how many
// numbers have been added. It assumes the arrays have been created big enough to not
// have overflow. It is used to remember the coordinates of our solution.
void Maze::addToArrays(int xVal, int yVal)
{
   solutionX[numPoints] = xVal;
   solutionY[numPoints] = yVal;
   numPoints++;
}
// Return true or false if moving to the specified coordinate is valid
// Return false if we have been to this cell already
bool Maze::validMove(int newX, int newY)
{
   // Check for going off the maze edges
   if (newX < 0 || newX >= WIDTH)
   return false;
   if (newY < 0 || newY >= HEIGHT)
   return false;
   // Check if target is a wall
   if (maze[newY][newX]=='X')
   return false;
   // Check if visited
   if (visited[newY][newX])
   return false;
   return true;
}
// Make the move on the maze to move to a new coordinate
// I passed curX and curY by reference so they are changed to
// the new coordinates. Here we assume the move coordinates are valid.
// This returns true if we move onto the exit, false otherwise.
// Also update the visited array.
bool Maze::move(int &curX, int &curY, int newX, int newY)
{
   bool foundExit = false;
   if (maze[newY][newX]=='E') // Check for exit
   foundExit = true;
   curX = newX; // Update location
   curY = newY;
   visited[curY][curX] = true;
   return foundExit;
}
// Display the maze in ASCII
void Maze::printMaze(int curx, int cury)
{
   for (int y=0; y < HEIGHT;y++)
   {
       for (int x=0; x < WIDTH; x++)
       {
           if ((x==curx) && (y==cury))
           cout << "@";
           else
           cout << maze[y][x];
       }
       cout << endl;
   }
}
// Recursively search from x,y until we find the exit
bool Maze::search(int x, int y)
{
   bool foundExit;
   if (maze[y][x]=='E')
       return true;
   visited[y][x]=true;
   if (validMove(x,y-1))
       foundExit = search(x,y-1);
   if (!foundExit && (validMove(x,y+1)))
       foundExit = search(x,y+1);
   if (!foundExit && (validMove(x-1,y)))
       foundExit = search(x-1,y);
   if (!foundExit && (validMove(x+1,y)))
       foundExit = search(x+1,y);
   if (foundExit)
   {
       // Remember coordinates we found the exit in the solution arrays
       addToArrays(x, y);
       return true;
   }
   return false;
}
int main()
{
   Maze m;
   m.randomFill();
   m.printPath();
}

Add a comment
Know the answer?
Add Answer to:
I NEED HELP IN MAZE PROBLEM. Re-write the following program using classes. The design is up...
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
  • why do i get this syntax error? for example: i have these two classes: class Maze...

    why do i get this syntax error? for example: i have these two classes: class Maze { private: int row, col; cell **arr; public: Maze(int r = 0, int c = 0) { this->row = r; this->col = c; arr = new cell*[row]; for (int i = 0; i < row; i++) arr[i] = new cell[col]; } }; class cell { private: bool visited; bool up, down, right, left; int x, y; int px, py; char status; public: cell() {...

  • Need help in c++ programming to output the lines in my code: if word if found:...

    Need help in c++ programming to output the lines in my code: if word if found:            cout << "'" << word << "' was found in the grid" << endl;            cout << "'" << word << "' was not found in the grid" << endl; The words can be touching if they are horizontally, vertically, or diagonally adjacent. For example, the board: Q W E R T A S D F G Z X C V B Y U A...

  • I need help solving this basic C++ question. I need help fixing my code.   Question: Design...

    I need help solving this basic C++ question. I need help fixing my code.   Question: Design a class called a box that represents a box. Box classes have variables such as the length of the box, width, and height. 1. Member variables shall be dedicated members. 2. Define the creator of the Box Class. The creator may receive all of the data and may not receive any. 3. Add accessor and creator 4. Add an empty function, which indicates whether...

  • The Problem A robot is asked to navigate a maze. It is placed at a certain...

    The Problem A robot is asked to navigate a maze. It is placed at a certain position (the starting position) in the maze and is asked to try to reach another position (the goal position). Positions in the maze will either be open or blocked with an obstacle. Positions are identified by (x,y) coordinates. At any given moment, the robot can only move 1 step in one of 4 directions. Valid moves are: ● Go North: (x,y) -> (x,y-1) ●...

  • I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<i...

    I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<iostream> using namespace std; const int ROWS=3; const int COLS=3; void fillBoard(char [][3]); void showBoard(char [][3]); void getChoice(char [][3],bool); bool gameOver(char [][3]); int main() { char board[ROWS][COLS]; bool playerToggle=false; fillBoard(board); showBoard(board); while(!gameOver(board)) { getChoice(board,playerToggle); showBoard(board); playerToggle=!playerToggle; } return 1; } void fillBoard(char board[][3]) { for(int i=0;i<ROWS;i++) for(int j=0;j<COLS;j++) board[i][j]='*'; } void showBoard(char board[][3]) { cout<<" 1 2 3"<<endl; for(int i=0;i<ROWS;i++) { cout<<(i+1)<<"...

  • I have a queue and stack class program that deals with a palindrome, I need someone...

    I have a queue and stack class program that deals with a palindrome, I need someone to help to put in templates then rerun the code. I'd greatly appreciate it. It's in C++. Here is my program: #include<iostream> #include<list> #include<iterator> #include<string> using namespace std; class Queue { public: list <char> queue; Queue() { list <char> queue; } void Push(char item) { queue.push_back(item); } char pop() { char first = queue.front(); queue.pop_front(); return first; } bool is_empty() { if(queue.empty()) { return...

  • Maze Solving with Stacks Problem Statement Consider a maze made up of rectangular array of squares,...

    Maze Solving with Stacks Problem Statement Consider a maze made up of rectangular array of squares, such as the following one: X X X X X X X X X X X X X           X            X X X X    X X X           X               X     X X X     X X    X    X     X     X X X         X          X             X X X     X X X X X                X X X X X X X X X X X X X Figure...

  • In C++ please.. I only need the game.cpp. thanks. Game. Create a project titled Lab8_Game. Use...

    In C++ please.. I only need the game.cpp. thanks. Game. Create a project titled Lab8_Game. Use battleship.h, battleship.cpp that mentioned below; add game.cpp that contains main() , invokes the game functions declared in battleship.h and implements the Battleship game as described in the introduction. ——————————————- //battleship.h #pragma once // structure definitions and function prototypes // for the battleship assignment // 3/20/2019 #include #include #ifndef BATTLESHIP_H_ #define BATTLESHIP_H_ // // data structures definitions // const int fleetSize = 6; // number...

  • create a program shape.cpp that uses classes point.h and shape.h. The program should compile using the...

    create a program shape.cpp that uses classes point.h and shape.h. The program should compile using the provided main program testShape.cpp. the provided programs should not be modified. Instructions ar egiven below. Shape class The Shape class is an abstract base class from which Rectangle and Circle are derived. bool fits_in(const Rectangle& r) is a pure virtual function that should return true if the Shape fits in the Rectangle r. void draw(void) is a pure virtual function that writes the svg...

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
ADVERTISEMENT