My current recursive function works to a degree, but then ruins itself when it goes back down the stack.
void Graph::findPath( Room * curRoom )
{
if( curRoom -> myNumber == 0 )
{
cout << "Outside.\n";
//Escape the recursion!
}
else
{
curRoom -> visited = true;
if( curRoom -> North -> visited == false )
{
escapePath[ _index ] = "North";
cout << "_index: " << _index << "\n";
++_index;
findPath( curRoom -> North );
cout << "_index: " << _index << "\n";
escapePath[ _index ] = "";
--_index;
}
if( curRoom -> East -> visited == false )
{
escapePath[ _index ] = "East";
cout << "_index: " << _index << "\n";
++_index;
findPath( curRoom -> East );
cout << "_index: " << _index << "\n";
escapePath[ _index ] = "";
--_index;
}
if( curRoom -> South -> visited == false )
{
escapePath[ _index ] = "South";
cout << "_index: " << _index << "\n";
++_index;
findPath( curRoom -> South );
cout << "_index: " << _index << "\n";
escapePath[ _index ] = "";
--_index;
}
if( curRoom -> West -> visited == false )
{
escapePath[ _index ] = "West";
cout << "_index: " << _index << "\n";
++_index;
findPath( curRoom -> West );
cout << "_index: " << _index << "\n";
escapePath[ _index ] = "";
--_index;
}
}
}
To save you some reading, the idea is that the base case is finding 0. Otherwise it tries four different cardinal directions, which is a different numbered room. Every time it makes a move, it adds the move it made to an external array, and every time it comes back up it removes that step from the stack.
My issue is that it has the correct path stored when it finds the 0, but removes it on the way back up.
Is there a way to escape it, such as a break.
No gotos or exceptions
There is a way to exit recursion using exceptions, but I wouldn’t recommend it. Instead, modify your function to return a bool that indicates whether you’ve found 0 or not and modify your logic to return from the function without changing path if 0 has been found. Here’s the illustration of the idea: