Skip to content

Commit 7d29522

Browse files
authored
Merge pull request #354 from Hardvan/connected_components_cpp
Add `ConnectedComponents.cpp`
2 parents 6e41059 + bfb7e9a commit 7d29522

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -652,8 +652,8 @@ In order to achieve greater coverage and encourage more people to contribute to
652652
</a>
653653
</td>
654654
<td> <!-- C++ -->
655-
<a href="./CONTRIBUTING.md">
656-
<img align="center" height="25" src="./logos/github.svg" />
655+
<a href="./src/cpp/ConnectedComponents.cpp">
656+
<img align="center" height="25" src="./logos/cplusplus.svg" />
657657
</a>
658658
</td>
659659
<td> <!-- Java -->

src/cpp/ConnectedComponents.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
#define VERTICES 6
5+
#define INF -1
6+
7+
std::vector<bool> visited(VERTICES, false); // Array to track visited vertices
8+
int components = 0;
9+
10+
// Adjacency matrix representing the graph
11+
int matrix[VERTICES][VERTICES] = {{0, INF, 1, INF, INF, INF},
12+
{INF, 0, INF, 1, 1, INF},
13+
{1, INF, 0, INF, INF, INF},
14+
{INF, 1, INF, 0, 1, 1},
15+
{INF, 1, INF, 1, 0, 1},
16+
{INF, INF, INF, 1, 1, 0}};
17+
18+
// Recursive method to find connected components using adjacency matrix
19+
void findConnectedComponents(int current)
20+
{
21+
for (int i = 0; i < VERTICES; i++)
22+
{
23+
if (!visited[i] && matrix[current][i] == 1)
24+
{
25+
visited[i] = true;
26+
components++;
27+
std::cout << "(" << i << ")-";
28+
findConnectedComponents(i);
29+
}
30+
}
31+
}
32+
33+
int main()
34+
{
35+
// Initialize all vertices as unvisited
36+
for (int i = 0; i < VERTICES; i++)
37+
visited[i] = false;
38+
39+
// For each vertex, if it is unvisited, start a DFS and count components
40+
for (int i = 0; i < VERTICES; i++)
41+
{
42+
if (!visited[i])
43+
{
44+
components = 0;
45+
visited[i] = true;
46+
std::cout << "Starting at vertex (" << i << ")-";
47+
findConnectedComponents(i);
48+
std::cout << "\nNumber of connected components starting from vertex " << i << ": " << components << "\n\n";
49+
}
50+
}
51+
52+
return 0;
53+
}

0 commit comments

Comments
 (0)