有向图的连通性
要检查图的连通性,我们将尝试使用任何遍历算法遍历所有节点。完成遍历后,如果有任何节点未访问,则表示该图不是连通的。

对于有向图,我们将从所有节点开始遍历以检查连通性。有时一个边只有一个向外边而没有向内边,因此从任何其他起始节点都无法访问该节点。
在这种情况下,遍历算法是递归 DFS 遍历。
输入和输出
Input: Adjacency matrix of a graph 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 Output: The Graph is connected.
算法
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.
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP