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

65 lines
1.1 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
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> &);
2020-05-18 19:41:15 +08:00
public:
explicit graph(int n) : adj(n, vector<int>()) { connected_components = 0; }
2020-05-18 19:41:15 +08:00
void addEdge(int, int);
int getConnectedComponents()
{
depth_first_search();
return connected_components;
2020-05-18 19:41:15 +08:00
}
2020-05-18 18:44:51 +08:00
};
void graph::addEdge(int u, int v)
{
adj[u - 1].push_back(v - 1);
adj[v - 1].push_back(u - 1);
2020-05-18 18:44:51 +08:00
}
void graph::depth_first_search()
{
int n = adj.size();
vector<bool> visited(n, false);
2020-05-18 18:44:51 +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
}
}
void graph::explore(int u, vector<bool> &visited)
{
visited[u] = true;
for (auto v : adj[u])
{
if (!visited[v])
{
explore(v, visited);
}
2020-05-18 19:18:26 +08:00
}
2020-05-18 18:44:51 +08:00
}
int main()
{
graph g(4);
g.addEdge(1, 2);
g.addEdge(3, 2);
std::cout << g.getConnectedComponents();
return 0;
2020-05-18 18:44:51 +08:00
}