0% found this document useful (0 votes)
8 views2 pages

4 - Topological Sort

Uploaded by

Charlie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

4 - Topological Sort

Uploaded by

Charlie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

3

.Implement and analyze topological sorting for a given graph.

#include<stdio.h>
void ts(int a[20][20], int n)
{
int t[10], vis[10], stack[10],i,j,indeg[10],top=0,ele,k=1;

for(i=1;i<=n;i++)
{
t[i]=0;
vis[i]=0;
indeg[i]=0;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i][j]==1)
{
indeg[j]=indeg[j]+1;
}
}
}
printf("\n Indegree array :");
for(i=1;i<=n;i++)
printf("%d",indeg[i]);
for(i=1;i<=n;i++)
{
if(indeg[i]==0)
{
stack[++top]=i;
vis[i]=1;
}
}
while(top>0)
{
ele = stack[top--];
t[k++]=ele;
for(j=1;j<=n;j++)
{
if(a[ele][j]==1 && vis[j]==0)
{
indeg[j]=indeg[j]-1;
if(indeg[j]==0)
{
stack[++top]=j;
vis[j]=1;
}
}
}
}
printf("\n Topological Sorting \n");
for(i=1;i<=n;i++)
printf("%d ",t[i]);
}

int main()
{
int n, a[10][10],i,j;
printf("Enter no. of vertices : ");
scanf("%d",&n);
printf("\n Enter Adjacency matrix : \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",a[i][j]);
}
}
ts(a,n);
return 0;
}

Enter the number of nodes:


4

Enter the adjacent matrix


0100
0010
0001
0000
Topological ordering is:
1234

You might also like