
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
// Graph adjacency list node
typedef struct Node {
int vertex;
struct Node* next;
} Node;
// Graph structure
typedef struct Graph {
int numVertices;
Node* adjLists[MAX_VERTICES];
int visited[MAX_VERTICES];
} Graph;
Node* createNode(int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
Graph* createGraph(int vertices) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->numVertices = vertices;
for (int i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(Graph* graph, int src, int dest) {
Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}
void dfs(Graph* graph, int vertex, int* stack, int* stackIndex) {
graph->visited[vertex] = 1;
Node* temp = graph->adjLists[vertex];
while (temp) {
int adjVertex = temp->vertex;
if (!graph->visited[adjVertex]) {
dfs(graph, adjVertex, stack, stackIndex);
}
temp = temp->next;
}
stack[(*stackIndex)++] = vertex;
}
void dfsTranspose(Graph* graph, int vertex, int* visited) {
visited[vertex] = 1;
Node* temp = graph->adjLists[vertex];
while (temp) {
int adjVertex = temp->vertex;
if (!visited[adjVertex]) {
dfsTranspose(graph, adjVertex, visited);
}
temp = temp->next;
}
}
Graph* getTranspose(Graph* graph) {
Graph* gT = createGraph(graph->numVertices);
for (int v = 0; v < graph->numVertices; v++) {
Node* temp = graph->adjLists[v];
while (temp) {
addEdge(gT, temp->vertex, v);
temp = temp->next;
}
}
return gT;
}
int kosarajuSCC(Graph* graph) {
int stack[MAX_VERTICES];
int stackIndex = 0;
for (int i = 0; i < graph->numVertices; i++) {
if (!graph->visited[i]) {
dfs(graph, i, stack, &stackIndex);
}
}
Graph* transposeGraph = getTranspose(graph);
int visited[MAX_VERTICES] = {0};
int count = 0;
for (int i = stackIndex - 1; i >= 0; i--) {
int v = stack[i];
if (!visited[v]) {
dfsTranspose(transposeGraph, v, visited);
count++;
}
}
return count;
}
int main() {
int V = 5;
Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 1, 2);
addEdge(graph, 2, 0);
addEdge(graph, 3, 4);
int sccCount = kosarajuSCC(graph);
printf("Number of Strongly Connected Components: %d\n", sccCount);
return 0;
}