-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPROGRAM TO IMPLEMENT TOPOLOGICAL SORTING.CPP
More file actions
71 lines (63 loc) · 1.18 KB
/
Copy pathPROGRAM TO IMPLEMENT TOPOLOGICAL SORTING.CPP
File metadata and controls
71 lines (63 loc) · 1.18 KB
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
//PROGRAM TO IMPLEMENT TOPOLOGICAL SORTING
#include<iostream.h>
#include<conio.h>
#include<process.h>
int a[10][10],adj[10][10],n,reach[10]={0},start;
void dfs(int s)
{
if(start!=s)
{
a[start][s]=1;
}
reach[s]=1;
for(int i=0;i<n;i++)
if(adj[s][i]!=0&&!reach[i])
dfs(i);
}
void main()
{
clrscr();
cout<<"\nEnter the number of verticies :";
cin>>n;
cout<<"\nEnter the adjacency matrix :\n";
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>adj[i][j];
/*checking for cycles*/
for(start=0;start<n;start++)
dfs(start);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(a[i][j]==1&&a[j][i]==1)
{
cout<<"This graph contains cycles";
getch();
exit(0);
}
int index[10];
for(i=0;i<n;i++)
index[i]=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
index[i]+=adj[j][i];
int sol[10],k=0;
while(k<n-1)
{
for(i=0;i<n;i++)
{
if(index[i]==0)
{
sol[k]=i+1;
k++;
index[i]=-1;
for(int l=0;l<n;l++)
if(adj[i][l]==1)
index[l]-=1;
}
}
}
cout<<"\nTopological Sequence :\n";
for(i=0;i<n;i++)
cout<<" "<<sol[i];
getch();
}