Question

In the following graph, write a Java program using Topological Sort.

b.


please write java code and show me the output.

Thank you :)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:  
import java.io.*;
import java.util.*;
  

public class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; // Adjacency List
  
//Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
  
// Function to add an edge into the graph
void addEdge(int v,int w) { adj[v].add(w); }
  
// A recursive function used by topologicalSort
void topologicalSortUtil(int v, boolean visited[],
Stack stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i;
  
  
Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())
{
i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack);
}
  
// Push current vertex to stack which stores result
stack.push(new Integer(v));
}
  

void topologicalSort()
{
Stack stack = new Stack();
  
// Mark all the vertices as not visited
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
  
// Call the recursive helper function to store
// Topological Sort starting from all vertices
// one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);
  
// Print contents of stack
while (stack.empty()==false)
System.out.print(stack.pop() + " ");
}
  
// Driver method
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g = new Graph(8);
g.addEdge(0, 1);
g.addEdge(0, 3);
g.addEdge(1, 2);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 5);
g.addEdge(4, 6);
g.addEdge(5, 6);
g.addEdge(5, 7);
  
System.out.println("Following is a Topological " +
"sort of the given graph");
g.topologicalSort();
}
}

OUTPUT:

Following is a Topological sort of the given graph
0 3 4 5 7 6 1 2 

NOTE: Consider

a as 0,

b as 1,

c as 2,

d as 3,

e as 4,

f as 5,

g as 6,

h as 7

Add a comment
Know the answer?
Add Answer to:
In the following graph, write a Java program using Topological Sort. please write java code and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT