用 C++ 檢查有向圖是否聯通


為了檢查圖的連通性,我們將嘗試使用任何遍歷演算法遍歷所有節點。遍歷完成後,如果仍有未訪問的節點,則該圖是不連通的。

對於有向圖,我們將從所有節點開始遍歷以檢查連通性。有時一條邊可能只有外向邊,沒有內向邊,因此該節點將不會從任何其他起始節點訪問。

在這種情況下,遍歷演算法是遞迴 DFS 遍歷。

輸入 - 圖的鄰接矩陣

01000
00100
00011
10000
01000

輸出 - 該圖是連通的。

演算法

traverse(u, visited)
Input: The start node u and the visited node to mark which node is visited.
Output: Traverse all connected vertices.
Begin
   mark u as visited
   for all vertex v, if it is adjacent with u, do
      if v is not visited, then
         traverse(v, visited)
   done
End
isConnected(graph)
Input: The graph.
Output: True if the graph is connected.
Begin
   define visited array
   for all vertices u in the graph, do
      make all nodes unvisited
      traverse(u, visited)
      if any unvisited node is still remaining, then
         return false
   done
   return true
End

示例

 活動演示

#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 0, 0, 0},
   {0, 0, 1, 0, 0},
   {0, 0, 0, 1, 1},
   {1, 0, 0, 0, 0},
   {0, 1, 0, 0, 0}
};
void traverse(int u, bool visited[]){
   visited[u] = true; //mark v as visited
   for(int v = 0; v<NODE; v++){
      if(graph[u][v]){
         if(!visited[v])
         traverse(v, visited);
      }
   }
}
bool isConnected(){
   bool *vis = new bool[NODE];
   //for all vertex u as start point, check whether all nodes are visible or not
   for(int u; u < NODE; u++){
      for(int i = 0; i<NODE; i++)
      vis[i] = false; //initialize as no node is visited
      traverse(u, vis);
      for(int i = 0; i<NODE; i++){
         if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
         return false;
      }
   }
   return true;
}
int main(){
   if(isConnected())
   cout << "The Graph is connected.";
   else
   cout << "The Graph is not connected.";
}

輸出

The Graph is connected.

更新於: 2019 年 9 月 25 日

1K+ 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.