DATA STRUCTURES PROGRAM • GRAPHS

Count Strongly Connected Components with Kosaraju's Algorithm

Learn how to count strongly connected components with kosaraju's algorithm using a clear C program.

AdvancedKosarajuTranspose graphSCC

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Strongly connected components = 3

COMPLETE C PROGRAM

Complete C implementation

dsa-strongly-connected-components.c
Open in compiler
#include <stdio.h>

void finish(int vertex, int graph[5][5], int visited[5], int order[5], int *top)
{
    visited[vertex] = 1;
    for (int next = 0; next < 5; next++)
        if (graph[vertex][next] && !visited[next]) finish(next, graph, visited, order, top);
    order[(*top)++] = vertex;
}
void mark(int vertex, int graph[5][5], int visited[5])
{
    visited[vertex] = 1;
    for (int next = 0; next < 5; next++)
        if (graph[vertex][next] && !visited[next]) mark(next, graph, visited);
}

int main(void)
{
    int graph[5][5] = {{0}}, transpose[5][5] = {{0}};
    int edges[][2] = {{1,0},{0,2},{2,1},{0,3},{3,4}};
    for (int index = 0; index < 5; index++) {
        graph[edges[index][0]][edges[index][1]] = 1;
        transpose[edges[index][1]][edges[index][0]] = 1;
    }
    int visited[5] = {0}, order[5], top = 0;
    for (int vertex = 0; vertex < 5; vertex++)
        if (!visited[vertex]) finish(vertex, graph, visited, order, &top);
    for (int vertex = 0; vertex < 5; vertex++) visited[vertex] = 0;
    int components = 0;
    while (top > 0) {
        int vertex = order[--top];
        if (!visited[vertex]) { mark(vertex, transpose, visited); components++; }
    }
    printf("Strongly connected 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

Strongly connected components = 3
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Process the transposed graph in reverse finish order from the original DFS.
  3. Display the computed result.

Process the transposed graph in reverse finish order from the original DFS.

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.