mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-14 19:00:15 +08:00
formatting source-code for 153fb7b8a5
This commit is contained in:
@@ -3,8 +3,7 @@
|
||||
|
||||
using std::vector;
|
||||
|
||||
class graph
|
||||
{
|
||||
class graph {
|
||||
private:
|
||||
vector<vector<int>> adj;
|
||||
int connected_components;
|
||||
@@ -14,48 +13,39 @@ class graph
|
||||
public:
|
||||
explicit graph(int n) : adj(n, vector<int>()) { connected_components = 0; }
|
||||
void addEdge(int, int);
|
||||
int getConnectedComponents()
|
||||
{
|
||||
int getConnectedComponents() {
|
||||
depth_first_search();
|
||||
return connected_components;
|
||||
}
|
||||
};
|
||||
|
||||
void graph::addEdge(int u, int v)
|
||||
{
|
||||
void graph::addEdge(int u, int v) {
|
||||
adj[u - 1].push_back(v - 1);
|
||||
adj[v - 1].push_back(u - 1);
|
||||
}
|
||||
|
||||
void graph::depth_first_search()
|
||||
{
|
||||
void graph::depth_first_search() {
|
||||
int n = adj.size();
|
||||
vector<bool> visited(n, false);
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (!visited[i])
|
||||
{
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (!visited[i]) {
|
||||
explore(i, visited);
|
||||
connected_components++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void graph::explore(int u, vector<bool> &visited)
|
||||
{
|
||||
void graph::explore(int u, vector<bool> &visited) {
|
||||
visited[u] = true;
|
||||
for (auto v : adj[u])
|
||||
{
|
||||
if (!visited[v])
|
||||
{
|
||||
for (auto v : adj[u]) {
|
||||
if (!visited[v]) {
|
||||
explore(v, visited);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int main() {
|
||||
graph g(4);
|
||||
g.addEdge(1, 2);
|
||||
g.addEdge(3, 2);
|
||||
|
||||
Reference in New Issue
Block a user