
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>
#include <stdbool.h>
#define MAX 100
void reverseGraph(int V, int adj[][MAX], int revAdj[][MAX], int outDegree[], int size[]) {
for (int u = 0; u < V; u++) {
for (int j = 0; j < size[u]; j++) {
int v = adj[u][j];
revAdj[v][size[v]++] = u;
outDegree[u]++;
}
}
}
void eventualSafeNodes(int V, int adj[][MAX], int size[]) {
int revAdj[MAX][MAX] = {0};
int revSize[MAX] = {0};
int outDegree[MAX] = {0};
bool safe[MAX] = {false};
int queue[MAX], front = 0, rear = 0;
reverseGraph(V, adj, revAdj, outDegree, size);
for (int i = 0; i < V; i++) {
if (outDegree[i] == 0) queue[rear++] = i;
}
while (front < rear) {
int node = queue[front++];
safe[node] = true;
for (int j = 0; j < revSize[node]; j++) {
int neighbor = revAdj[node][j];
if (--outDegree[neighbor] == 0) {
queue[rear++] = neighbor;
}
}
}
printf("Safe Nodes: ");
for (int i = 0; i < V; i++) {
if (safe[i]) printf("%d ", i);
}
printf("\n");
}
int main() {
int V = 7;
int adj[MAX][MAX] = {
{1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}
};
int size[MAX] = {2, 2, 1, 1, 1, 0, 0};
eventualSafeNodes(V, adj, size);
return 0;
}| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(V + E) | Even in the best case (e.g., an acyclic graph), we must traverse all vertices and edges to identify safe nodes. |
| Average Case | O(V + E) | Each node and edge is visited once, whether it's part of a cycle or not. |
| Worst Case | O(V + E) | In graphs with deep chains or many dependencies, the traversal still touches all vertices and edges once. |