-
Notifications
You must be signed in to change notification settings - Fork 1
/
topological.c
90 lines (77 loc) · 1.65 KB
/
topological.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<stdio.h>
#include<stdlib.h>
int V, E, dfstime;
int finished[1000],discover[1000], marked[1000];
struct node {
int info;
struct node * next;
}*adj[100], *head;
void addEdge (int x , int y)
{
struct node* edge = (struct node *) malloc(sizeof(struct node));
edge->info = y;
edge->next = adj[x];
adj[x] = edge;
}
void insertnode (int k)
{
struct node *x = (struct node*)malloc(sizeof(struct node));
x->info = k;
x->next = head;
head = x;
}
void dfsvisit (int s)
{
discover[s] = ++dfstime;
marked[s] = 1;
struct node *x = adj[s];
while (x != NULL) {
if (!marked[x->info])
dfsvisit(x->info);
x = x->next;
}
insertnode(s);
finished[s] = ++dfstime;
}
void dfs ()
{
for (int i = 1; i < V+1; ++i)
marked[i] = 0;
dfstime = 0;
for (int i = 1; i < V+1; ++i)
if (!marked[i]) dfsvisit(i);
}
void printTopSort (struct node *x) {
while (x!= NULL) {
printf("%d ",x->info);
x = x->next;
}
}
int main()
{
V = 6, E = 8;
addEdge(1,2);
addEdge(2,3);
addEdge(3,4);
addEdge(4,2);
addEdge(1,4);
addEdge(5,4);
addEdge(5,6);
addEdge(6,6);
for (int i = 1; i < V+1; ++i) {
struct node *x = adj[i];
printf("\n%d - ",i);
while (x != NULL) {
printf("%d ",x->info);
x = x->next;
}
printf("\n");
}
dfs();
for (int i = 1; i < V+1; ++i) printf("%d ",discover[i]);
printf("\n");
for (int i = 1; i < V+1; ++i) printf("%d ",finished[i]);
printf("\n Topological sort : ");
printTopSort(head);
return 0;
}