For the maze program, with '*' indicating a wall, ' ' indicating a corridor, and '#' indicating a solution path, where I have to use a recursive backtracking algorithm, I am still having trouble print the maze solution. Here is the unsolved maze:
8 12
**********
* * *
* ****** *
***** *
* ******
*** *** *
* ** *
**********
Here is the solved maze:
##**********
*#*########*
*###******#*
*****######*
* ###******
***#***####*
* #####**#*
**********##
Here is my updated solution:
#include<iostream>
#include<fstream>
using namespace std;
#define MAXROW 24 // Maximum number of rows
#define MAXCOL 81 // Maximum number of columns
// Read a maze from a file.
void readMaze(ifstream &in, int &rows, int &columns, char a[MAXROW][MAXCOL])
{
in >> rows >> columns;
cout << rows << " " << columns << endl;
in.getline(a[0],sizeof a[0]);
for(int i = 0; i < rows; i++)
{
in.getline(a[i], sizeof a[i]);
}
}
// Print the maze.
void printMaze(int &rows, int &columns, char a[MAXCOL][MAXCOL])
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
cout << a[i][j];
}
cout << endl;
}
}
// Solve the maze using recursion.
bool solveMaze(int rows, int columns, char a[MAXROW][MAXCOL])
{
// If outside the maze, return false.
if(rows < 0 || rows > MAXCOL-1 || columns < 0 || columns > MAXROW-1)
{
return false;
}
// If there is a wall, return false.
if(a[columns][rows] == '*')
{
return false;
}
// Mark solution path.
a[columns][rows] = '#';
// If able to move up, return true.
if(solveMaze(rows,columns-1,a))
{
return true;
}
// If able to move right, return true.
if(solveMaze(rows+1,columns,a))
{
return true;
}
// If able to move down, return true.
if(solveMaze(rows,columns+1,a))
{
return true;
}
// If able to move left, return true.
if(solveMaze(rows-1,columns,a))
{
return true;
}
// Mark repeated paths.
a[columns][rows] = 'x';
return false;
}
int main()
{
char inFile[20];
char a[MAXROW][MAXCOL];
ifstream in;
int rows, columns;
// Prompt user for file name.
cout << "Enter file name: ";
cin >> inFile;
// Check for file open errors.
if(!inFile)
{
cout << "Error" << endl;
return -1;
}
// Open the file.
in.open(inFile);
cout << "Maze before solution: " << endl;
readMaze(in,rows,columns,a);
printMaze(rows,columns,a);
cout << "Maze after solution: " << endl;
solveMaze(rows,columns,a);
printMaze(rows,columns,a);
// Close the file.
in.close();
return 0;
}
I made a few changes to my code and I still cannot get the solved maze output. Is there anything else I need to change/fix?