在 看 严蔚敏的 数据结构 一书 7.5小节时,书上 说“ 判断有向图是否存在环要比无向图复杂。对于无向图来说,深度优先遍历过程中遇到回边(即指向已访问过的顶点的边),则必定存在环路”。 看的不明白,所以 网上 百度了一下。
有了思路:故写下算法 和思路,以便以后 温故。
思路:
1.一个n个顶点,e条边的 无向图,若 e>= n,必有环路。
2.若 e < n ,需要 深度 遍历,并把 父节点传入 参数中,如果 遇到 一个 节点 被访问过 并且 不是 父节点,那么 就有环路。
上代码:
void dfsCycle(Graph g,int curent,int parent,bool * isVisited,bool * is){
isVisited[curent] = true;
ArcNode * next = g.list[curent].head->nextArc;
for (; next != NULL; next = next->nextArc)
{
int index = next->adjVex;
if (isVisited[index] == false){
dfsCycle(g,index,curent,isVisited,is);
}
else if(index != parent){
*is = true;
}
}
}
bool isCycle(Graph g){
if (g.arcNum >= g.vexNum){
r