C++ 程序检查无向图的连通性使用 BFS
想要检查图的连接性,我们将尝试使用任意遍历算法遍历所有节点。遍历完成后,如果仍有未访问的节点,则说明图不是连通的。

对于无向图,我们将选择一个节点并从中进行遍历。
本例中,遍历算法是递归 BFS 遍历。
输入 − 图的邻接矩阵
| 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(s, visited)
输入 − 开始节点 s 和 visited 节点,用于标记哪个节点已被访问。
输出 − 遍历所有连接的顶点。
Begin
mark s as visited
insert s into a queue Q
until the Q is not empty, do
u = node that is taken out from the queue
for each node v of the graph, do
if the u and v are connected, then
if u is not visited, then
mark u as visited
insert u into the queue Q.
done
done
EndisConnected(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示例代码 (C++)
#include<iostream>
#include<queue>
#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 s, bool visited[]) {
visited[s] = true; //mark v as visited
queue<int> que;
que.push(s);//insert s into queue
while(!que.empty()) {
int u = que.front(); //delete from queue and print
que.pop();
for(int i = 0; i < NODE; i++) {
if(graph[i][u]) {
//when the node is non-visited
if(!visited[i]) {
visited[i] = true;
que.push(i);
}
}
}
}
}
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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP