java實現檢測閉環的方法:
*
* 功能:判斷網路中是否存在閉環
* 作者:pieryon
* @param nodeCollections
* @return
* @throws Exception
*/
public boolean isContainLoop(Map<String,Map<String,Object>> nodeCollections) throws Exception{
//用map的hash碼計算,速度更快
Map<String,String> visitedList = new HashMap<String, String>();
/**
* 初始化"起點
*/
String startNode = getOrigin(nodeCollections);
boolean containLoop = false ;
/**
* 初始化"視野"
*/
Map<String,String> nodeName = new HashMap<String, String>() ;
nodeName.put("nextNode", startNode);
nodeName.put("curNode", startNode);
nodeName.put("beforeNode", startNode);
int count = 0 ;
/**
* 如果當前不含有閉環,並且沒有遍歷完起點節點的所有分支則進入循環
*/
while(!containLoop
&& !(nodeName.get("beforeNode").equals(nodeName.get("curNode"))
&& nodeName.get("nextNode") == null )){
nodeName = traverse(nodeCollections, nodeName, visitedList);
if(count > 1){
containLoop = containSameNode(visitedList,nodeName.get("nextNode"));
}
count ++ ;
}
return containLoop;
}