0% found this document useful (0 votes)
7 views3 pages

TOPSORT

Uploaded by

vijaykrishna2k24
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)
7 views3 pages

TOPSORT

Uploaded by

vijaykrishna2k24
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/ 3

#include <stdio.

h>
#define MAX 10
int i;

// Adjacency matrix representing the graph


int a[MAX][MAX] = { // 0 1 2 3 4 5 6
{0, 1, 1, 0, 0, 0, 0}, // 0
{0, 0, 1, 0, 0, 1, 0}, // 1
{0, 0, 0, 1, 0, 0, 0}, // 2
{0, 0, 0, 0, 0, 0, 0}, // 3
{0, 0, 0, 0, 0, 0, 0}, // 4
{0, 0, 0, 1, 1, 0, 0}, // 5
{0, 1, 0, 0, 0, 1, 0} // 6
};

int stack[30], que[30], vis[30];


int top = -1, fr = -1, rr = -1, n = 7;

// Function to add an element to the queue


void add(int x) {
if (rr < 0) fr++;
rr++;
que[rr] = x;
}

// Function to push an element onto the stack


void push(int x) {
stack[++top] = x;
}

// Function to pop an element from the stack


int pop() {
return stack[top--];
}

// Depth-First Search (DFS) function


void dfs(int u) {
vis[u] = 1;
for (int i = 0; i < n; i++) {
if (vis[i] == 0 && a[u][i] != 0) {
dfs(i);
}
}
push(u);
}

// Topological Sort function


void topsort() {
int i;
top = -1;
rr = -1;

for (i = 0; i < n; i++)


vis[i] = 0;

for (i = 0; i < n; i++) {


if (vis[i] == 0)
dfs(i);
}

while (top >= 0) {


add(pop());
}
}

int main() {
int seq[10][MAX];
topsort();

printf("Topological Sort Order:\n");


for (int i = 0; i < n; i++) {
seq[0][i] = que[i];
printf("%6d", que[i]);
}
printf("\n");

return 0;
}

You might also like