如何在达到某个深度后从递归中停止此递归函数?

时间:2015-12-12 07:01:02

标签: c# recursion collections ienumerable

我有这个功能,我希望它“爬树”,直到达到指定的深度限制。当它达到该极限时,它应该停止攀爬并继续进行集合中的下一个元素并再次开始攀爬树。我有点困难,需要一些帮助。现在,我的代码无法编译。

   private int _depth;
   private Dictionary<Alliance, BehaviourType> _allianceMap = new Dictionary<Alliance, BehaviourType>();        

    private bool HasInCommon(Alliance other)
    {
         int currentDepth = 0;
         return RecursiveHasInCommon(other, ref currentDepth);
    }

    private bool RecursiveHasInCommon(Alliance other)
    {
        foreach (var obj in other._allianceMap)
        {
            if (_allianceMap.ContainsKey(obj.Key))
            {
                return true;
            }
            int currentDepth = 0;
            while (currentDepth < _depth)
            {
                RecursiveHasInCommon(obj.Key);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

在递归函数上添加深度参数并在开头检查

int maxDepth = 5;

private bool HasInCommon(Alliance other)
{
     return RecursiveHasInCommon(other);
}

private bool RecursiveHasInCommon(Alliance other, int depth = 0) //default value of 0
{
    if(++depth > maxDepth)
        return false;
    ...
        RecursiveHasInCommon(obj.Key, depth); // send current depth
    ...
}