2015-12-12 85 views
-1

我有這個功能,我希望它「爬樹」,直到達到指定的深度限制。當它達到這個極限時,它應該停止攀爬並繼續收集下一個元素,然後重新開始爬樹。我有點卡住,需要一些幫助。現在,我的代碼不能編譯。如何在達到一定深度後從遞歸中停止遞歸函數?

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); 
      } 
     } 
    } 
+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 
    ... 
}