使用DFS检查无向图连通性的C++程序
要检查图的连通性,我们将尝试使用任何遍历算法遍历所有节点。遍历完成后,如果存在任何未访问的节点,则该图未连接。
对于无向图,我们将选择一个节点并从中进行遍历。
在本例中,遍历算法是递归深度优先搜索 (DFS) 遍历。
输入 − 图的邻接矩阵
0 | 1 | 1 | 0 | 0 |
1 | 0 | 1 | 1 | 0 |
1 | 1 | 0 | 1 | 1 |
0 | 1 | 1 | 0 | 1 |
0 | 0 | 1 | 1 | 0 |
输出 − 图是连通的。
算法
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)
输入 − 图。
输出 − 如果图是连通的,则返回真。
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, 1, 0, 0}, {1, 0, 1, 1, 0}, {1, 1, 0, 1, 1}, {0, 1, 1, 0, 1}, {0, 0, 1, 1, 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.
广告