標籤:判斷無向圖是否有環路 無向圖是否有環問題
在 看 嚴蔚敏的 資料結構 一書 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){return true;}bool isVisited[MAX_VERTEX_NUM] = {false};bool is = false;for (int i = 0; i < g.vexNum; i++){if (isVisited[i] == false){dfsCycle(g,i,-1,isVisited,&is);if (is){//存在環路,退出函數return true;}}}return is;}int _tmain(int argc, _TCHAR* argv[]){Graph g;graphCreate(&g);printGrahp(g);char * is = isCycle(g) ? "有環路" : "沒有環路";printf("圖 %s\n",is);//及時銷毀記憶體是個好習慣graphDestory(&g);return 0;}運行:
完整代碼 網盤地址:點擊開啟連結
看資料結構寫代碼(44) 判斷無向圖是否有環路