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;
}