Problem 3: Finding Graph Cycles
采用深度优先搜索(递归),寻找图中是否存在循环
之所以用currvisited和visited是因为可能图是非连通图,一次遍历不一定能遍历完所有的结点
bool RecCyclicCheck(graphT & graph, nodeT * node, Set<nodeT *> & visited)
{
if (visited.contains(node)){
return true;
}
Set<arcT *>::Iterator arcIter = node->connected.iterator();
bool result = false;
visited.add(node);
while (!result && arcIter.hasNext())
{
if (RecCyclicCheck(graph, arcIter.next()->end, visited)){
result = true;
}
}
//visited.remove(node);
return result;
}
bool IsCyclicGraph(graphT & graph)
{
Set<nodeT *>::Iterator iter = graph.allNodes.iterator();
Set<nodeT *> visited;
while(iter.hasNext())
{
Set<nodeT *> currVisited;
nodeT * currStart = iter.next();
if(!visited.contains(currStart) &&
RecCyclicCheck(graph, currStart, currVisited))
return true;
visited.unionWith(currVisited);
}
return false;
}