我当前的递归函数在某种程度上起作用,但是当它回到堆栈时会自行消失.
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了节省一些阅读,我们的想法是基本情况是找到0.否则它会尝试四个不同的基本方向,这是一个不同的编号房间.每次进行移动时,它都会添加对外部数组所做的移动,每次重新启动它都会从堆栈中移除该步骤.
我的问题是它在找到0时存储了正确的路径,但在备份的路上将其删除.
有没有办法逃脱它,比如休息.
没有任何例外
vit*_*aut 18
有一种方法可以使用异常退出递归,但我不推荐它.相反,修改您的函数以返回一个bool,指示您是否找到0并修改您的逻辑以从函数返回而不更改路径(如果已找到0).这是这个想法的例证:
bool Graph::findPath( Room * curRoom )
{
if( curRoom -> myNumber == 0 )
{
cout << "Outside.\n";
//Escape the recursion!
return true;
}
// ...
if (findPath( curRoom -> North ))
return true;
// ...
return false;
}
Run Code Online (Sandbox Code Playgroud)