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.

IntermediateConnected componentsDFS forestUndirected graph

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Components = 2

COMPLETE C PROGRAM

Complete C implementation

dsa-graph-connected-components.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Components = 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Start a new DFS whenever the vertex loop finds an unvisited component.
  3. 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.