TheAlgorithms-C-Plus-Plus/graph/connected_components.cpp

56 lines
1.0 KiB
C++
Raw Normal View History

2020-05-18 18:44:51 +08:00
#include <iostream>
#include <vector>
2020-05-18 19:18:26 +08:00
using std::vector;
2020-05-18 18:44:51 +08:00
2020-05-18 19:18:26 +08:00
class graph {
2020-05-18 19:41:15 +08:00
private:
vector<vector<int>> adj;
int connected_components;
void depth_first_search();
void explore(int, vector<bool>&);
public:
explicit graph(int n): adj(n, vector<int>()) {
connected_components = 0;
}
void addEdge(int, int);
int getConnectedComponents() {
depth_first_search();
return connected_components;
}
2020-05-18 18:44:51 +08:00
};
2020-05-18 19:18:26 +08:00
void graph::addEdge(int u, int v) {
2020-05-18 18:44:51 +08:00
adj[u-1].push_back(v-1);
adj[v-1].push_back(u-1);
}
2020-05-18 19:18:26 +08:00
void graph::depth_first_search() {
2020-05-18 18:44:51 +08:00
int n = adj.size();
2020-05-18 19:18:26 +08:00
vector<bool> visited(n, false);
2020-05-18 18:44:51 +08:00
2020-05-18 19:18:26 +08:00
for (int i = 0 ; i < n ; i++) {
if (!visited[i]) {
explore(i, visited);
connected_components++;
2020-05-18 18:44:51 +08:00
}
}
}
2020-05-18 19:18:26 +08:00
void graph::explore(int u, vector<bool> &visited) {
2020-05-18 18:44:51 +08:00
visited[u] = true;
2020-05-18 19:18:26 +08:00
for (auto v : adj[u]) {
if (!visited[v]) {
explore(v, visited);
}
2020-05-18 18:44:51 +08:00
}
}
2020-05-18 19:18:26 +08:00
int main() {
2020-05-18 18:44:51 +08:00
graph g(4);
2020-05-18 19:27:00 +08:00
g.addEdge(1, 2);
g.addEdge(3, 2);
2020-05-18 19:18:26 +08:00
std::cout << g.getConnectedComponents();
2020-05-18 18:44:51 +08:00
return 0;
}