#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 100
// Queue structure for BFS
typedef struct {
int items[MAX_NODES];
int front, rear;
} Queue;
void initQueue(Queue* q) {
q->front = 0;
q->rear = -1;
}
int isEmpty(Queue* q) {
return q->rear < q->front;
}
void enqueue(Queue* q, int val) {
q->items[++q->rear] = val;
}
int dequeue(Queue* q) {
return q->items[q->front++];
}
// Graph adjacency list
typedef struct Node {
int vertex;
struct Node* next;
} Node;
Node* createNode(int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
void addEdge(Node* adj[], int src, int dest) {
Node* newNode = createNode(dest);
newNode->next = adj[src];
adj[src] = newNode;
}
void kahnTopologicalSort(Node* adj[], int n) {
int inDegree[MAX_NODES] = {0};
int i;
// Calculate in-degree of each node
for (i = 0; i < n; i++) {
Node* temp = adj[i];
while (temp) {
inDegree[temp->vertex]++;
temp = temp->next;
}
}
Queue q;
initQueue(&q);
// Enqueue nodes with in-degree 0
for (i = 0; i < n; i++) {
if (inDegree[i] == 0) {
enqueue(&q, i);
}
}
int count = 0;
int topOrder[MAX_NODES];
while (!isEmpty(&q)) {
int u = dequeue(&q); // Remove node with no dependencies
topOrder[count++] = u;
// Decrease in-degree of neighbors
Node* temp = adj[u];
while (temp) {
inDegree[temp->vertex]--;
if (inDegree[temp->vertex] == 0) {
enqueue(&q, temp->vertex);
}
temp = temp->next;
}
}
// Check if there was a cycle
if (count != n) {
printf("Graph has a cycle, topological sort not possible\n");
return;
}
// Print topological order
for (i = 0; i < count; i++) {
printf("%d", topOrder[i]);
if (i != count - 1) printf(" -> ");
}
printf("\n");
}
int main() {
int n = 4;
Node* adj[MAX_NODES] = {NULL};
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 2, 3);
kahnTopologicalSort(adj, n);
return 0;
}
for (i = 0; i < n; i++) {
Node* temp = adj[i];
while (temp) {
inDegree[temp->vertex]++;
temp = temp->next;
}
}
Calculate in-degree of each node by counting incoming edges
for (i = 0; i < n; i++) {
if (inDegree[i] == 0) {
enqueue(&q, i);
}
}
Add all nodes with zero in-degree to the queue to start processing
while (!isEmpty(&q)) {
int u = dequeue(&q);
topOrder[count++] = u;
Remove node with no dependencies and add to topological order
Node* temp = adj[u];
while (temp) {
inDegree[temp->vertex]--;
if (inDegree[temp->vertex] == 0) {
enqueue(&q, temp->vertex);
}
temp = temp->next;
}
Decrease in-degree of neighbors and enqueue if they become zero
if (count != n) {
printf("Graph has a cycle, topological sort not possible\n");
return;
}
Detect cycle if not all nodes are processed