看資料結構寫代碼(44) 判斷無向圖是否有環路

來源:互聯網
上載者:User

標籤:判斷無向圖是否有環路   無向圖是否有環問題   

在 看 嚴蔚敏的 資料結構 一書 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) 判斷無向圖是否有環路

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.