-
Notifications
You must be signed in to change notification settings - Fork 267
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #354 from Hardvan/connected_components_cpp
Add `ConnectedComponents.cpp`
- Loading branch information
Showing
2 changed files
with
55 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |