
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 100
int inDegree[MAX] = {0};
int adj[MAX][MAX];
int queue[MAX];
int front = 0, rear = 0;
void enqueue(int x) {
queue[rear++] = x;
}
int dequeue() {
return queue[front++];
}
int main() {
int nodes = 3;
int edges[3][2] = {{0, 1}, {1, 2}, {2, 0}}; // change this to test different graphs
for (int i = 0; i < 3; i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u][v] = 1;
inDegree[v]++;
}
for (int i = 0; i < nodes; i++) {
if (inDegree[i] == 0)
enqueue(i);
}
int visited = 0;
while (front < rear) {
int current = dequeue();
visited++;
for (int j = 0; j < nodes; j++) {
if (adj[current][j]) {
inDegree[j]--;
if (inDegree[j] == 0)
enqueue(j);
}
}
}
if (visited == nodes)
printf("No cycle detected.\n");
else
printf("Cycle detected.\n");
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(V + E) | Even in the best case, we must visit each node and each edge at least once to calculate in-degrees and simulate the process. |
| Average Case | O(V + E) | Each node and its edges are processed exactly once while maintaining the in-degree and queue. |
| Worst Case | O(V + E) | The algorithm still processes every node and edge regardless of the presence or absence of cycles. |