Question

In: Computer Science

An excellent example of a program that can be greatly simplified by the use of recursion...

An excellent example of a program that can be greatly simplified by the use of recursion is the Chapter 4 case study, escaping a maze. As already explained, in each maze cell the mouse stores on the maze stack up to four cells neighboring the cell in which it is currently located. The cells put on the stack are the ones that should be investigated after reaching a dead end. It does the same for each visited cell. Write a program that uses recursion to solve the maze problem. Use the following pseudocode:

exitCell(currentCell)

if currentCell is the exit

  success;

  else exitCell(the passage above currentCell);

  exitCell(the passage below currentCell);

exitCell(the passage left to currentCell);

  exitCell(the passage right to currentCell);

Here is the code from the Chapter 4 Case Study:

#include <iostream>

#include <string>

#include <stack>

using namespace std;

template<class T>

class Stack : public stack<T> {

public:

T pop() {

T tmp = top();

stack<T>::pop();

return tmp;

}

};

class Cell {

public:

Cell(int i = 0, int j = 0) {

x = i; y = j;

}

bool operator== (const Cell& c) const {

return x == c.x && y == c.y;

}

private:

int x, y;

friend class Maze;

};

class Maze {

public:

Maze();

void exitMaze();

private:

Cell currentCell, exitCell, entryCell;

const char exitMarker, entryMarker, visited, passage, wall;

Stack<Cell> mazeStack;

char **store; // array of strings;

void pushUnvisited(int,int);

int rows, cols;

friend ostream& operator<< (ostream& out, const Maze& maze) {

for (int row = 0; row <= maze.rows+1; row++)

out << maze.store[row] << endl;

out << endl;

return out;

}

};

Maze::Maze() : exitMarker('e'), entryMarker('m'), visited('.'),

passage('0'), wall('1') {

Stack<char*> mazeRows;

char str[80], *s;

int col, row = 0;

cout << "Enter a rectangular maze using the following "

<< "characters:\nm - entry\ne - exit\n1 - wall\n0 - passage\n"

<< "Enter one line at at time; end with Ctrl-z:\n";

while (cin >> str) {

row++;

cols = strlen(str);

s = new char[cols+3]; // two more cells for borderline columns;

mazeRows.push(s);

strcpy(s+1,str);

s[0] = s[cols+1] = wall; // fill the borderline cells with 1s;

s[cols+2] = '\0';

if (strchr(s,exitMarker) != 0) {

exitCell.x = row;

exitCell.y = strchr(s,exitMarker) - s;

}

if (strchr(s,entryMarker) != 0) {

entryCell.x = row;

entryCell.y = strchr(s,entryMarker) - s;

}

}

rows = row;

store = new char*[rows+2]; // create a 1D array of pointers;

store[0] = new char[cols+3]; // a borderline row;

for ( ; !mazeRows.empty(); row--) {

store[row] = mazeRows.pop();

}

store[rows+1] = new char[cols+3]; // another borderline row;

store[0][cols+2] = store[rows+1][cols+2] = '\0';

for (col = 0; col <= cols+1; col++) {

store[0][col] = wall; // fill the borderline rows with 1s;

store[rows+1][col] = wall;

}

}

void Maze::pushUnvisited(int row, int col) {

if (store[row][col] == passage || store[row][col] == exitMarker) {

mazeStack.push(Cell(row,col));

}

}

void Maze::exitMaze() {

int row, col;

currentCell = entryCell;

while (!(currentCell == exitCell)) {

row = currentCell.x;

col = currentCell.y;

cout << *this; // print a snapshot;

if (!(currentCell == entryCell))

store[row][col] = visited;

pushUnvisited(row-1,col);

pushUnvisited(row+1,col);

pushUnvisited(row,col-1);

pushUnvisited(row,col+1);

if (mazeStack.empty()) {

cout << *this;

cout << "Failure\n";

return;

}

else currentCell = mazeStack.pop();

}

cout << *this;

cout << "Success\n";

}

int main() {

Maze().exitMaze();

return 0;

Solutions

Expert Solution

The answer of the above problem is given below :

#include <iostream>
#include <string.h>
#include <stack>

using namespace std;
template<class T>
class Stack : public stack<T>
{
public:
T pop()
{
T tmp = stack<T>::top();
stack<T>::pop();
return tmp;
}
};

class Cell
{
public:
/*Constructor function for Cell */
Cell(int i = 0, int j = 0)
{
x = i;
y = j;
}
/*Operator overloading for "==" */
bool operator == (const Cell& c) const
{
return x == c.x && y == c.y;
}

private:
int x, y;
/*A friend class can access private and protected
members of other class in which it is declared as friend.*/
friend class Maze;
};

class Maze
{
public:
Maze();
void exitMaze();
private:
Cell currentCell, exitCell, entryCell;
const char exitMarker, entryMarker, visited, passage, wall;
Stack<Cell> mazeStack;
char **store;
void pushUnvisited(int,int);
int rows, cols;

/*Operator overloading for "<<" to support stream insertion of Maze object */
friend ostream& operator << (ostream& out, const Maze& maze)
{
for (int row = 0; row <= maze.rows+1; row++)
out << maze.store[row] << endl;
out << endl;
return out;
}
};

Maze::Maze() : exitMarker('E'), entryMarker('M'), visited('.'),
passage('0'), wall('1')
{
Stack<char*> mazeRows;
char str[80], *s;
int col, row = 0;
cout << "Enter a Rectangular Maze Using the following "
<< "Characters:\nM - Entry\nE - Exit\n1 - Wall\n0 - Passage\n"
<< "Enter one line at at time; end with Ctrl-z:\n";

/*Insert the Maze pattern */
while (cin >> str)
{
row++;
cols = strlen(str);

/*two more cells for borderline columns;*/
s = new char[cols+3];
mazeRows.push(s);
strcpy(s+1,str);

/* fill the borderline cells with 1s;*/
s[0] = s[cols+1] = wall;
s[cols+2] = '\0';

if (strchr(s,exitMarker) != 0)
{
exitCell.x = row;
exitCell.y = strchr(s,exitMarker) - s;
}
if (strchr(s,entryMarker) != 0)
{
entryCell.x = row;
entryCell.y = strchr(s,entryMarker) - s;
}
}
rows = row;
store = new char*[rows+2]; /* create a 1D array of pointers; */
store[0] = new char[cols+3]; /*a borderline row; */
for ( ; !mazeRows.empty(); row--)
{
store[row] = mazeRows.pop();
}
store[rows+1] = new char[cols+3]; /*another borderline row; */
store[0][cols+2] = store[rows+1][cols+2] = '\0';

for (col = 0; col <= cols+1; col++)
{
store[0][col] = wall; /* fill the top borderline row with 1s;*/
store[rows+1][col] = wall; /* fill the bottom borderline row with 1s;*/
}
}

void Maze::pushUnvisited(int row, int col)
{
/*If Current cell is either passage Cell or exit Cell
then push it to the Stack */
if (store[row][col] == passage || store[row][col] == exitMarker)
{
mazeStack.push(Cell(row,col));
}
}

void Maze::exitMaze()
{
int row, col;
currentCell = entryCell;

/*Actual iteration to solve the Maze problem */
while (!(currentCell == exitCell))
{
row = currentCell.x;
col = currentCell.y;

/* cout << *this; */

if (!(currentCell == entryCell))
store[row][col] = visited;

/*Visit neighboring Cell for Solution */
pushUnvisited(row-1,col);
pushUnvisited(row+1,col);
pushUnvisited(row,col-1);
pushUnvisited(row,col+1);

/*If Stack is Empty means all the connected passage
from Entry cell has been Visited */
if (mazeStack.empty())
{
cout << *this;
cout << "Failure\n";
return;
}
else
currentCell = mazeStack.pop();
}
cout << *this;
cout << "Success\n";
}
/*Driver Function */
int main()
{
Maze().exitMaze();
return 0;
}
The screenshots of the code are as below :

Output Screen of the code is :

Thanks for liking the post.

For any query related to the post , Please comment !!!


Related Solutions

/*Use recursion in the function: void getDigit( int num) /* Try this program and implement the...
/*Use recursion in the function: void getDigit( int num) /* Try this program and implement the function void getDigit( intnum) so that it displays the digits in a given number. For example, the number, 1234 consist of 1, 2, 3 and 4. This is an exercise to demonstate the use of a recursive function and the use of recusrion in C++ */ #include #include using namespace std; int main() {      int num;      cout <<"Enter an integer: ";     ...
Write a program in python that implements quicksort, first using recursion and then without recursion.
Write a program in python that implements quicksort, first using recursion and then without recursion.
please use java swing and recursion and the suggested method hints listed Objective: Write a program...
please use java swing and recursion and the suggested method hints listed Objective: Write a program in which draws (yes it actually makes a picture) a triangular fractal using recursion. This is best if done using a java applet. Suggested Methodology The idea for it is this First draw a filled equilateral triangle Next draw another filled equilateral triangle of a different color that’s upside down in the middle of that triangle Using the other triangles formed repeat step 2...
Rewrite your program for finding Pascal's Triangle to use iteration (loops) instead of recursion. Include in...
Rewrite your program for finding Pascal's Triangle to use iteration (loops) instead of recursion. Include in both algorithms code to keep track of the total time used to run the algorithms in milliseconds. Run these algorithms for n = 10, n = 20, and n = 30. Print out both the original output and the time to run for both algorithms. Please make sure you comment your code thoroughly. The code should be nicely formatted and should use proper variables.
Use recursion function to derive computation time for Binary Search by drawing a recursion tree diagram...
Use recursion function to derive computation time for Binary Search by drawing a recursion tree diagram and using algebra calculation.
lineage program to Memheck-clean. The program is a simplified family tree manager. It maintains a list...
lineage program to Memheck-clean. The program is a simplified family tree manager. It maintains a list of Persons in a PersonList. Each Person object maintains a set of pointers to his/her parents as well as to his/her children. The code contains several memory leaks. To compile: please highlight the changes $g++ -g -O0 -fno-inline *.cpp -o lineage code linage.cpp // Adapted from http://people.cs.ksu.edu/~sherrill/labs/lab05/lineage.cpp #include "person.h" #include "personList.h" int main() {     PersonList theList;     theList.addPerson("Bob", "Mark", "Betty");     theList.addPerson("Jim", "Bob",...
C++ Remove every other node in a circular linked list USING RECURSION. You can only use...
C++ Remove every other node in a circular linked list USING RECURSION. You can only use the preprocessor directives <iostream> and using namespace std; You must use this prototype: int remove_every_other(node *&rear)
Java Programming: Can I get an example of a program that will allow 4 options? Example...
Java Programming: Can I get an example of a program that will allow 4 options? Example Output: Choose on of the options below: 1. Display all items in CSV file. (CSV file includes for example brand of phone, size, price) 2. Pick an item by linear searching 3. Pick an item by bineary searching 4. Quit Program
Recursion Discussions Question: Why would you want to use recursion? Concerning programming, when would you want...
Recursion Discussions Question: Why would you want to use recursion? Concerning programming, when would you want to use iterative vs. recursive programming? Where does coding fit in concerning the software process (i.e. its use in design, in coding, etc.)? Describe recursion problems, and why does it seem to fit with recursion? (e.g. nature, math, music, sports game, etc.)  
   This example illustrates that the climate in one country greatly impacts the food supply in...
   This example illustrates that the climate in one country greatly impacts the food supply in another country. Why is this an example of global interdependence? Check all that apply. It illustrates the impact globalization has on the food system. It illustrates that supply and demand chains between countries can be disrupted by events in one country. It illustrates the struggle developing countries face in a globalized economy.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT