|
| 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