This repository has been archived by the owner on Sep 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toposort.c
136 lines (118 loc) · 2.35 KB
/
toposort.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
Write a program to determine the Topological sort of a given graph using
i. Depth-First technique
ii. Source removal technique
https://github.com/my-lambda-projects
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *arr;
int top;
} stack;
stack *Stack(int size) {
stack *new = malloc(sizeof(stack));
new->arr = malloc(size * sizeof(int));
new->top = -1;
return new;
}
void push(stack *s, int vertex) {
s->arr[++s->top] = vertex;
}
int g[10][10];
int V;
int visited[10];
void dfsv(int v, stack *s)
{
// printf("Visiting %d\n", v);
visited[v] = 1;
int i;
for(i = 0; i < V; ++i)
{
if(!(visited[i]) && (g[v][i] == 1) && (i != v)) {
dfsv(i, s);
push(s, i);
}
}
}
void dfs_sort()
{
stack *s = Stack(2 * V);
int i;
for(i = 0; i < V; ++i)
{
if(!visited[i]) {
dfsv(i, s);
push(s, i);
}
push(s, i);
}
printf("Toposort: ");
for(i=V-1; i>=0; --i)
printf("%d ", s->arr[i]);
printf("\n");
}
void source_removal() {
int *in_degree = calloc(V, sizeof(int));
for(int i = 0; i < V; ++i) {
for(int j = 0; j < V; ++j)
in_degree[i] += g[j][i];
}
stack *s = Stack(V);
for(int i = 0; i < V; ++i)
if(in_degree[i] == 0)
push(s, i);
printf("Toposort: ");
while(s->top != -1) {
int v = s->arr[s->top--];
printf("%d ", v);
for(int i = 0; i < V; ++i) {
if(g[v][i] != 0) {
g[v][i] = 0;
--in_degree[i];
if(in_degree[i] == 0)
push(s, i);
}
}
}
printf("\n");
}
int main()
{
printf("Enter the Number of Vertices: \n");
scanf("%d", &V);
int i, j;
printf("Enter the Adjacency Matrix: \n");
for(i = 0; i < V; ++i)
{
for(j = 0; j < V; ++j)
scanf(" %d", &g[i][j]);
}
dfs_sort();
source_removal();
return 0;
}
/*
Enter the Number of Vertices:
6
Enter the Adjacency Matrix:
0 1 0 0 0 0
0 0 1 1 0 0
0 0 0 0 1 0
0 0 0 0 1 1
0 0 0 0 0 1
0 0 0 0 0 0
Toposort: 0 1 3 2 4 5
Toposort: 0 1 3 2 4 5
Enter the Number of Vertices:
6
Enter the Adjacency Matrix:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 1 0 0 0 0
1 1 0 0 0 0
1 0 1 0 0 0
Toposort: 2 3 1 1 0 0
Toposort: 5 2 3 4 1 0
*/