Skip to content

Commit

Permalink
Merge pull request #354 from Hardvan/connected_components_cpp
Browse files Browse the repository at this point in the history
Add `ConnectedComponents.cpp`
  • Loading branch information
kelvins authored Oct 11, 2024
2 parents 6e41059 + bfb7e9a commit 7d29522
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -652,8 +652,8 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- C++ -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/cpp/ConnectedComponents.cpp">
<img align="center" height="25" src="./logos/cplusplus.svg" />
</a>
</td>
<td> <!-- Java -->
Expand Down
53 changes: 53 additions & 0 deletions src/cpp/ConnectedComponents.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <iostream>
#include <vector>

#define VERTICES 6
#define INF -1

std::vector<bool> visited(VERTICES, false); // Array to track visited vertices
int components = 0;

// Adjacency matrix representing the graph
int matrix[VERTICES][VERTICES] = {{0, INF, 1, INF, INF, INF},
{INF, 0, INF, 1, 1, INF},
{1, INF, 0, INF, INF, INF},
{INF, 1, INF, 0, 1, 1},
{INF, 1, INF, 1, 0, 1},
{INF, INF, INF, 1, 1, 0}};

// Recursive method to find connected components using adjacency matrix
void findConnectedComponents(int current)
{
for (int i = 0; i < VERTICES; i++)
{
if (!visited[i] && matrix[current][i] == 1)
{
visited[i] = true;
components++;
std::cout << "(" << i << ")-";
findConnectedComponents(i);
}
}
}

int main()
{
// Initialize all vertices as unvisited
for (int i = 0; i < VERTICES; i++)
visited[i] = false;

// For each vertex, if it is unvisited, start a DFS and count components
for (int i = 0; i < VERTICES; i++)
{
if (!visited[i])
{
components = 0;
visited[i] = true;
std::cout << "Starting at vertex (" << i << ")-";
findConnectedComponents(i);
std::cout << "\nNumber of connected components starting from vertex " << i << ": " << components << "\n\n";
}
}

return 0;
}

0 comments on commit 7d29522

Please sign in to comment.