Spring 2009 CS 32
Homework 2
Time due: 9:00 PM Tuesday, April 28
Write a C++ function named pathExists that determines whether or not a there's a path from start to finish in a 10x10
maze. Here is the prototype:
bool pathExists(char maze[][10], int sr, int sc, int er, int ec);
// Return true if there is a path from (sr,sc) to (er,ec)
// through the maze; return false otherwise
The parameters are
A 2-dimensional 10x10 character array of Xs and dots that represents the maze. Each 'X' represents a wall, and each '.'
represents a walkway.
The starting coordinates in the maze: sr, sc; the row number and column number range from 0 to 9.
The ending coordinates in the maze: er, ec; the row number and column number range from 0 to 9.
The function must determine if there is a path from maze[sr][sc] to maze[er][ec] that includes only walkways, no walls.
The path may turn only north, east, south, and west, but not diagonally. You must use a stack data structure.
Your solution will use the following simple class, which represents an (r,c) coordinate pair:
class Coord
{
public:
Coord(int rr, int cc) : m_r(rr), m_c(cc) {}
int r() const { return m_r; }
int c() const { return m_c; }
private:
int m_r;
int m_c;
};
(Our convention is that (0,0) is the northwest (upper left) corner, with south (down) being the increasing r direction and
east (right) being the increasing c direction.)
The stack you must use is a stack of Coords. You may either write your own stack class, or use the stack class in the C+
+ Standard Library (pp. 309-311 in the textbook discuss that class). Here's an example of the relevant functions in the
library's stack class:
#include <stack>
using namespace std;
int main()
{
stack<Coord> coordStack;
// declare a stack of Coords
Coord a(5,6);
coordStack.push(a);
// push the coordinate (5,6)
coordStack.push(Coord(3,4)); // push the coordinate (3,4)
...
Coord b = coordStack.top();
// look at top item in the stack
coordStack.pop();
// remove the top item from stack
if (coordStack.empty())
// Is the stack empty?
cout << "empty!" << endl;
cout << coordStack.size() << endl;
// num of elements
}
Here is pseudocode for your function:
Push the starting coordinate onto the coordinate stack.
While the stack is not empty,
{
Pop the top coordinate off the stack. This gives you the current
(r,c) location that your algorithm is exploring.