Hi, in Jumping into C++, chapter 14, exercise 6 asks for building a maze, and then ensuring that it has a valid path.
Building a maze is simple, here's the code:
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
char GetChar(char &MazeChar);
int h;
int w;
char MazeChar;
int main()
{
srand(time(NULL));
cout << "Type in height of the maze: \n";
cin >> h;
cout << "Type in width of the maze: \n";
cin >> w;
char **Maze = new char*[h];
// filling the two-dimensional array with values
for (int i = 0; i < h; i++)
{
Maze[i] = new char[w];
}
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
GetChar(MazeChar);
Maze[i][j] = MazeChar;
}
}
// printing the maze
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
cout << Maze[i][j];
}
cout << "\n";
}
}
// code to get either " " or "X" and doing it randomly
char GetChar(char &MazeChar)
{
int CaseNr = 0;
CaseNr = rand() % 2;
switch (CaseNr)
{
case 0:
MazeChar = ' ';
break;
case 1:
MazeChar = 'X';
break;
}
}
It works, I can print a randomly generated maze
The maze: This program just prints some "spaces" and "X" characters in a two-dimensional array. X characters are the walls, and the maze is to go throught the spaces. Of course there's space between every line, but going horizontally through the space between the lines aren't allowed. Only going through ' ' characters is allowed.
But, how can I ensure that there's a valid path?
I tried putting this code after line 42 (before the printing loop), so that the program draws a valid path through the maze before printing the maze:
Code:
int SP;
SP = rand() % w;
Maze[0][SP] = ' ';
int CaseNr = 0;
int ph = 0;
int pw = SP;
while(ph != h)
{
CaseNr = rand() % 4;
switch(CaseNr)
{
case 0:
if(ph == h){break;}
ph = ph + 1;
Maze[ph][pw] = ' ';
break;
case 1:
if(ph == h){break;}
ph = ph + 1;
Maze[ph][pw] = ' ';
break;
case 2:
if(pw == 0){break;}
pw = pw - 1;
Maze[ph][pw] = ' ';
break;
case 3:
if(pw == w){break;}
pw = pw + 1;
Maze[ph][pw] = ' ';
break;
}
}
Putting this code didn't work, the program just crashes, and I don't know why.
But, how can I ensure that there's a randomly generated but valid path?