Thanks to visit codestin.com
Credit goes to www.scribd.com

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

ADA Lab Topological Sort Program 5

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

ADA Lab Topological Sort Program 5

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

Analysis & Design of Algorithms Lab-BCSL404 IV Semester

Design and implement C/C++ Program to obtain the Topological ordering of vertices in a
given digraph.

#include <stdio.h>

#define MAX 10

void sort(int a[MAX][MAX], int id[MAX], int temp[MAX], int n) {


int k = 0, i, j;
for (int count = 0; count < n; count++) {
for (i = 0; i < n; i++) {
if (id[i] == 0) {
id[i] = -1; // Mark as visited
temp[k++] = i;
for (j = 0; j < n; j++) {
if (a[i][j] == 1) {
id[j]--; // Reduce in-degree
}
}
break; // Restart loop after modifying in-degree
}
}
}

if (k != n)
printf("\nTopological ordering not possible (Cycle detected)");
else {
printf("\nTopological ordering is: ");
for (i = 0; i < k; i++)
printf("%d ", temp[i]);
}
}

int main() {
int a[MAX][MAX], id[MAX] = {0}, temp[MAX];
int n, i, j;

printf("\nEnter the number of vertices (n): ");


scanf("%d", &n);

printf("\nEnter the adjacency matrix:\n");


for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
if (a[i][j] == 1)

Dept. of CSE, SECAB. I. E. T., Vijayapur


Analysis & Design of Algorithms Lab-BCSL404 IV Semester

id[j]++; // Compute in-degree


}

sort(a, id, temp, n);

return 0;
}
**********************************OUTPUT1***************************

Enter the n value:6

Enter the graph data:


001100
000110
000101
000001
000001
000000

Topological ordering is: 1 2 3 4 5 6

*******************************OUTPUT2**************************

Enter the n value:4

Enter the graph data:


1432
5421
5342
4123

Topological ordering not possible(Cycle Detected)

Dept. of CSE, SECAB. I. E. T., Vijayapur

You might also like