1
+ // Helper structure to store DFS information for each vertex
2
+ typedef struct {
3
+ int dfn ; // Discovery time
4
+ int low ; // Lowest vertex reachable
5
+ int inStack ; // Whether vertex is in stack
6
+ } VertexInfo ;
7
+
8
+ // Helper function for Tarjan's algorithm
9
+ void Tarjan (Graph G , Vertex v , VertexInfo * info , Vertex * stack , int * top ,
10
+ int * time , void (* visit )(Vertex ), int * visited ) {
11
+ info [v ].dfn = info [v ].low = (* time )++ ;
12
+ stack [(* top )++ ] = v ;
13
+ info [v ].inStack = 1 ;
14
+
15
+ PtrToVNode node = G -> Array [v ];
16
+ while (node ) {
17
+ Vertex w = node -> Vert ;
18
+ if (info [w ].dfn == -1 ) { // Unvisited vertex
19
+ Tarjan (G , w , info , stack , top , time , visit , visited );
20
+ if (info [w ].low < info [v ].low )
21
+ info [v ].low = info [w ].low ;
22
+ } else if (info [w ].inStack ) { // Back edge to vertex in stack
23
+ if (info [w ].dfn < info [v ].low )
24
+ info [v ].low = info [w ].dfn ;
25
+ }
26
+ node = node -> Next ;
27
+ }
28
+
29
+ // If v is root of SCC, pop stack and print component
30
+ if (info [v ].dfn == info [v ].low ) {
31
+ Vertex w ;
32
+ do {
33
+ w = stack [-- (* top )];
34
+ info [w ].inStack = 0 ;
35
+ if (!visited [w ]) {
36
+ (* visit )(w );
37
+ visited [w ] = 1 ;
38
+ }
39
+ } while (w != v );
40
+ printf ("\n" ); // Print newline after each component
41
+ }
42
+ }
43
+
44
+ void StronglyConnectedComponents (Graph G , void (* visit )(Vertex V )) {
45
+ // Initialize arrays
46
+ VertexInfo * info = (VertexInfo * )malloc (G -> NumOfVertices * sizeof (VertexInfo ));
47
+ Vertex * stack = (Vertex * )malloc (G -> NumOfVertices * sizeof (Vertex ));
48
+ int * visited = (int * )calloc (G -> NumOfVertices , sizeof (int ));
49
+ int top = 0 ; // Stack top
50
+ int time = 0 ; // DFS timestamp
51
+
52
+ // Initialize vertex info
53
+ for (Vertex v = 0 ; v < G -> NumOfVertices ; v ++ ) {
54
+ info [v ].dfn = -1 ;
55
+ info [v ].low = -1 ;
56
+ info [v ].inStack = 0 ;
57
+ }
58
+
59
+ // Run Tarjan's algorithm for each unvisited vertex
60
+ for (Vertex v = 0 ; v < G -> NumOfVertices ; v ++ ) {
61
+ if (info [v ].dfn == -1 ) {
62
+ Tarjan (G , v , info , stack , & top , & time , visit , visited );
63
+ }
64
+ }
65
+
66
+ // Free memory
67
+ free (info );
68
+ free (stack );
69
+ free (visited );
70
+ }
0 commit comments