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.
This C++ program will use arrays, recursion, and pass by reference to calculate 02, 12, 22,...
This C++ program will use arrays, recursion, and pass by reference to calculate 02, 12, 22, 32, 42 and then print a message. Write a driver program (main) that includes the following: An array class (not a built-in-array) of 5 integers initialized to 0,1,2,3,4 the bases An integer initialized to 2 to hold the exponent A string initialized to “Good Job!\n”; A for loop that calls the recursive pow function with all of the bases and the exponent. Call the...
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.
To get some practice with recursion. You can do all this in one driver program. Write...
To get some practice with recursion. You can do all this in one driver program. Write a recursive method to compute the result of the Fibonacci sequence: Fibonacci(N) = Fibonacci(N -1) + Fibonacci(N-2) N == 0 is 0 N == 1 is 1 Testing: Display the result for Fibonacci(N) and the number of function calls for N = 2, 5 and 10.
This has to be a C program - Here is a simplified set of rules that...
This has to be a C program - Here is a simplified set of rules that show how a dive is judged at a competition like the Olympics: Each different kind of dive is given a "degree of difficulty". The limits on degrees of difficulty keep changing as competitors perform increasingly difficult dives, but for this assignment the degree of difficulty of each dive must be between 1 and 5 inclusive. The number of judges varies with the event, but...
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.
Solving Problems Using Recursion (Python): To solve the problem, you have to use recursion and cannot...
Solving Problems Using Recursion (Python): To solve the problem, you have to use recursion and cannot use for or while loops to solve the problems as well as not using global variables. 1. Create a function that takes a positive integer and returns it with neighboring digits removed. Do not convert the integer to a list. Ex. Input = [5555537777721] Output = [53721]
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",...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT