判断图是否连通可通过DFS、BFS或并查集实现:1)DFS从顶点0出发遍历,访问数等于总顶点数则连通;2)BFS同理,用队列逐层扩展;3)并查集将边两端合并,最后所有顶点根相同则连通。

在C++中判断图是否连通,主要针对无向图进行操作。如果图中任意两个顶点之间都存在路径,则称该图为连通图。以下是常用的几种判断方法。
从任意一个顶点出发,使用DFS遍历图,记录访问过的节点数量。若访问的节点数等于图的总顶点数,则图是连通的。
步骤如下:
#include <vector>
#include <iostream>
using namespace std;
void dfs(int u, vector<bool>& visited, const vector<vector<int>>& graph) {
visited[u] = true;
for (int v : graph[u]) {
if (!visited[v]) {
dfs(v, visited, graph);
}
}
}
bool isConnected(const vector<vector<int>>& graph, int n) {
vector<bool> visited(n, false);
dfs(0, visited, graph);
for (int i = 0; i < n; i++) {
if (!visited[i]) return false;
}
return true;
}
BFS与DFS思路一致,只是换用队列实现遍历。
立即学习“C++免费学习笔记(深入)”;
将起始点入队,逐层访问其邻居,标记已访问节点。结束后检查是否所有节点都被访问。
// BFS版本片段
bool isConnectedBFS(const vector<vector<int>>& graph, int n) {
vector<bool> visited(n, false);
queue<int> q;
q.push(0);
visited[0] = true;
int count = 1;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : graph[u]) {
if (!visited[v]) {
visited[v] = true;
q.push(v);
count++;
}
}
}
return count == n;
}
适用于边列表形式的图。通过合并每条边的两个顶点所在集合,最终判断所有顶点是否属于同一个集合。
int find(vector<int>& parent, int x) {
if (parent[x] != x)
parent[x] = find(parent, parent[x]);
return parent[x];
}
void unite(vector<int>& parent, int x, int y) {
int rx = find(parent, x), ry = find(parent, y);
if (rx != ry)
parent[rx] = ry;
}
bool isConnectedUnionFind(int n, const vector<pair<int, int>>& edges) {
vector<int> parent(n);
for (int i = 0; i < n; i++) parent[i] = i;
for (auto& e : edges) {
unite(parent, e.first, e.second);
}
int root = find(parent, 0);
for (int i = 1; i < n; i++) {
if (find(parent, i) != root)
return false;
}
return true;
}
以上就是c++++中如何判断图是否连通_c++图连通性判断方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号