Created
February 15, 2014 07:42
-
-
Save dnieh/9015767 to your computer and use it in GitHub Desktop.
Recursion to Solve a 2D String Array Maze
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; | |
bool pathExists(string maze[], int nRows, int nCols, 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 | |
{ | |
if (sr < 0 || sc < 0 || er < 0 || ec < 0 | |
|| sr > nRows || sc > nCols || er > nRows | |
|| ec > nCols) | |
return false; | |
if (sr == er && sc == ec) | |
return true; | |
// drop a bread crumb | |
maze[sr][sc] = '#'; | |
// north | |
if (maze[sr-1][sc] == '.' && pathExists(maze,nRows,nCols,sr-1,sc,er,ec) == true) | |
return true; | |
// east | |
if (maze[sr][sc+1] == '.' && pathExists(maze,nRows,nCols,sr,sc+1,er,ec) == true) | |
return true; | |
// south | |
if (maze[sr+1][sc] == '.' && pathExists(maze,nRows,nCols,sr+1,sc,er,ec) == true) | |
return true; | |
// west | |
if (maze[sr][sc-1] == '.' && pathExists(maze,nRows,nCols,sr,sc-1,er,ec) == true) | |
return true; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment