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

Pgm5 Topological Order

The document contains a C program that implements topological sorting using an adjacency matrix representation of a directed graph. It prompts the user to enter the number of nodes and the adjacency matrix, then calculates and displays the topological order of the nodes. The program handles multiple runs with different input matrices to demonstrate the sorting process.

Uploaded by

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

Pgm5 Topological Order

The document contains a C program that implements topological sorting using an adjacency matrix representation of a directed graph. It prompts the user to enter the number of nodes and the adjacency matrix, then calculates and displays the topological order of the nodes. The program handles multiple runs with different input matrices to demonstrate the sorting process.

Uploaded by

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

#include<stdio.

h>

int main()
{
int n; //no. of nodes
int a[10][10]; //Adjacency matrix
int i, j, k; //Index variables
int node; //To store next node to visit
int in[10] = {0}; //Stores indegree of each node
int v[10] = {0}; //To keep track of nodes visited

//1. Enter n
printf("Enter n: ");
scanf("%d", &n);

//2. Enter Adj matrix and find indegree


printf("Enter Adj matrix: \n");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
scanf("%d", &a[i][j]);

if(a[i][j] == 1) //updating indegree


in[j]++;
}
}

//3. Find topological order


printf("\nTopological order: ");
for(k=1; k<=n; k++)
{
//3a. Find node with indegree zero and mark it as visited
for(i=1; i<=n; i++)
{
if(in[i] == 0 && v[i] == 0)
{
node = i;
printf("%5d", node);
v[node] = 1;
break;
}
}

//3b. Update the indegree of other nodes


for(i=1; i<=n; i++)
if(a[node][i] == 1)
in[i]--;
}
printf("\n\n");
} //end of program
/*
Run 1:
Enter n: 5
Enter Adj matrix:
0 0 1 0 0
0 0 1 0 0
0 0 0 1 1
0 0 0 0 1
0 0 0 0 0

Topological order: 1 2 3 4 5

Run 2:
Enter n: 4
Enter Adj matrix:
0 1 0 0
0 0 0 1
1 1 0 1
0 0 0 0

Topological order: 3 1 2 4

Run 3:
Enter n: 4
Enter Adj matrix:
0 0 0 0
1 0 0 1
0 1 0 0
0 0 0 0

Topological order: 3 2 1 4
*/

You might also like