C++ 程式,利用 DFS 驗證有向圖的連通性


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

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

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

輸入:圖表的鄰接矩陣

01000
00100
00011
10000
01000

輸出:圖表是連通的。

演算法

traverse(u, visited)

輸入:起始節點 u 和已訪問的節點,用於標記已訪問的節點。

輸出:遍歷所有連線的頂點。

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)

輸入:圖表。

輸出:如果圖表是連通的,則為 True。

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.

更新於: 30-Jul-2019

538 次瀏覽

開啟您的職業

完成課程以獲得認證

開始
廣告