DATA STRUCTURES PROGRAM • GRAPHS
Count Connected Components in an Undirected Graph
Learn how to count connected components in an undirected graph using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Components = 2
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void mark(int vertex, int graph[6][6], int visited[6])
{
visited[vertex] = 1;
for (int neighbour = 0; neighbour < 6; neighbour++)
if (graph[vertex][neighbour] && !visited[neighbour]) mark(neighbour, graph, visited);
}
int main(void)
{
int graph[6][6] = {
{0,1,0,0,0,0}, {1,0,1,0,0,0}, {0,1,0,0,0,0},
{0,0,0,0,1,0}, {0,0,0,1,0,1}, {0,0,0,0,1,0}
};
int visited[6] = {0}, components = 0;
for (int vertex = 0; vertex < 6; vertex++)
if (!visited[vertex]) { mark(vertex, graph, visited); components++; }
printf("Components = %d\n", components);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Components = 2
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Start a new DFS whenever the vertex loop finds an unvisited component.
- Display the computed result.
Start a new DFS whenever the vertex loop finds an unvisited component.
EFFICIENCY
Time and space complexity
Time complexity
O(V²) with matrix
Auxiliary space
O(V)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
