Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading