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 次浏览

开启您的职业

完成课程以获得认证

开始
广告
© . All rights reserved.