求邻接矩阵的连通分量(DFS)
最近在看匈牙利匹配算法,相关学习记录下
下面是采用深度优先搜素的方式(DFS)找连通分量的简单C++示例代码
#include <iostream>
#include <vector>
using namespace std;
void dfs(int node, const vector<vector<int>>& graph, vector<bool>& visited, vector<int>& component) {
visited[node] = true;
component.push_back(node);
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited, component);
}
}
}
vector<vector<int>> findConnectedComponents(const vector<vector<int>>& graph) {
int numNodes = graph.size();
vector<bool> visited(numNodes, false);
vector<vector<int>> components;
for (int node = 0; node < numNodes; node++) {
if (!visited[node]) {
vector<int> component;
dfs(node, graph, visited, component);
components.push_back(component);
}
}
return components;
}
int main() {
vector<vector<int>> graph = {
{1, 2},
{0, 2},
{0, 1},
{7, 3},
{7, 4},
{6},
{5},
{3, 4}
};
vector<vector<int>> components = findConnectedComponents(graph);
cout << "Connected Components:" << endl;
for (const auto& component : components) {
for (int node : component) {
cout << node << " ";
}
cout << endl;
}
return 0;
}
在这段代码中,findConnectedComponents
函数接受一个邻接表表示的图,并返回一个包含连通分量的向量。dfs
函数用于深度优先搜索,它从给定的起始节点开始,遍历与之相连的所有未访问过的节点,并将它们添加到同一个连通分量中。在主函数中,我们使用一个示例图进行测试,并打印出图的连通分量。
运行结果:
Connected Components:
0 1 2
3 7 4
5 6