Needed in c++ using for, while, or do-while loops, and if/switch statements The
ID: 3791879 • Letter: N
Question
Needed in c++ using for, while, or do-while loops, and if/switch statements
The algorithm you are going to create will generate an maze based on a couple input parameters which will be read from the console.
A maze consists of a set of cells each of which can have up to four walls (though, ultimately, at most a cell will have is three). To create a maze, start by assuming all walls are in place and then, going left-to-right and up-to-down, for each cell randomly choose to remove the south or the west wall. Some cells the choice is predetermined; e.g., the cells along the west side of the maze all have south exits since the west wall is fixed.
For example, we might start with the following
The first cell cannot have an exit to the west so we remove the south exit.
In the next cell we randomly choose the west or south exit. Suppose it's west. We now have
Next, we might remove the south wall. So,
If we keep going, we might get something that looks like
In the end, there will always be a corridor along the west and south walls. This type of maze has the property that every cell can be reached from every other cell along a single path. I recommend trying this on a piece of graph paper using a coin to decide which exit to include. This might make it easier to conceptualize.
APP DETAILS
You may assume that the maze if 5x5.
Explanation / Answer
#include<iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int maze[5][5]; //Array representing each cell
int i,j;
// initialize random seed
srand(time(NULL));
for (i=0;i<5;i++){
for(j=0;j<5;j++){
if (j==0 && i == 4){
maze[i][j] == 0; //value for south-west cell both south and west side is close
} else if(j==0){ //Cells along west side
maze[i][j] = 2; // value 2 indicates that south side is open
} else if (i == 4){ //Cells along south side
maze[i][j] = 1; // Value 1 indicate that west side is open
} else {
maze[i][j] = rand()%2 + 1; //Random value for other cells
}
}
}
cout<<"+-+-+-+-+-+"<<endl; //North wall
for(i=0;i<5;i++){
for(j=0;j<5;j++){
if (maze[i][j] != 1) {
cout<<"| "; //West wall for each cell
}else{
cout<<" "; //Open west wall
}
}
cout<<"|"<<endl; //East wall
for(j=0;j<5;j++){
if (maze[i][j] != 2) {
cout<<"+-"; //South wall
}else{
cout<<"+ "; // Open south wall
}
}
cout<<"+"<<endl; //Itersection of south wall and east wall
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.