-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTSortDFS.c
47 lines (40 loc) · 1.08 KB
/
TSortDFS.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
#include <stdio.h>
#include <stdlib.h>
void topologicalSortDFSUtil(int v, int visited[], int stack[], int *top, int n, int a[20][20]) {
visited[v] = 1;
for (int i = 1; i <= n; i++) {
if (a[v][i] == 1 && !visited[i]) {
topologicalSortDFSUtil(i, visited, stack, top, n, a);
}
}
stack[++(*top)] = v;
}
void topologicalSortDFS(int n, int a[20][20]) {
int visited[20], stack[20], top = -1;
for (int i = 1; i <= n; i++) {
visited[i] = 0;
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
topologicalSortDFSUtil(i, visited, stack, &top, n, a);
}
}
printf("Topological Sort (DFS): ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}
int main() {
int n, a[20][20];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
scanf("%d", &a[i][j]);
}
}
topologicalSortDFS(n, a);
return 0;
}