2014-11-17 46 views
0

我有非循環情況檢測循環扶養在哈希映射在Java中

Tables => Set of Parent Tables [ HashMap<String, HashSet<String>> ] 

例的一個HashMap可能是:

A -> [B,C] 
D -> [B,C] 
B -> [C] 
c -> [] 

循環情況的例子是:

A -> [B,C] 
B -> [C] 
C -> [A] 

我想拒絕循環情況,因此需要一個函數來檢測提供的散列表是否有任何循環:

public boolean hasDependencies ( HashMap<String, HashSet<String>> objectAndItsDependentsMap) 
{ 
    //Implementation 
} 

我已閱讀文章,建議算法來檢測週期,但是作爲java的新手無法使用該知識來化妝上述功能。請幫忙!

回答

-1

這裏是只能在自己的例如基於粗略的實現。我建議測試其他例子。

public boolean hasDependencies(Map<String, Set<String>> objectAndItsDependentsMap) { 
    for (String node : objectAndItsDependentsMap.keySet()) { 
     final Set<String> directNeighbors = objectAndItsDependentsMap.get(node); 
     for (String directNeighbor : directNeighbors) { 
      Set<String> next = objectAndItsDependentsMap.get(directNeighbor); 
      while (next != null) { 
       for (String n : next) { 
        next = objectAndItsDependentsMap.get(n); 
        if (next != null && (next.contains(n) || next.contains(node))) { 
         return true; 
        } 
       } 
      } 
     } 
    } 
    return false; 
} 
+0

我感謝您的幫助在Java翻譯,但我認爲,如果我做我的例子稍微改變這個代碼將失敗如: a - > b,b - > c,c - > d,d - > a – lostcoderx

+0

@lostcoderx我編輯了我的答案,請檢查它現在是否適合您 – victorantunes

+0

代碼進入無限循環。 –