Question
In this assignment, you are already given an algorithm for topological sorting. 1. Run the topological sorting algorithm on Graph g1 defined in main. Note
In this assignment, you are already given an algorithm for topological sorting. 1. Run the topological sorting algorithm on Graph g1 defined in main. Note down the result somewhere. 2. For a topological sort to exist, the graph must not contain any cycles. Modify topologicalSort() method any way you like to handle such cases. The method now must print A cycle detected! in such a case. Test your code on Graph g2. 3. Current implementation of topologicalSort() uses queues. Implement a new topologicalSortStack() method so that the underlying data structure is now a stack. 4. Test this modified version with Graph g1. Is the result different from before? Does it mean your code is wrong? Explain in detail as a comment in your source code.
class Main { public static void main(String args[]) { // A graph Graph g1=new Graph(6); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(2, 3); g1.addEdge(3, 4); g1.addEdge(5, 2); g1.addEdge(5, 4); // A graph that contains a cycle Graph g2=new Graph(6); g2.addEdge(1, 2); g2.addEdge(2, 5); g2.addEdge(5, 0); g2.addEdge(5, 1); g2.addEdge(3, 4); g2.addEdge(4, 5); // Question 4: Comment here } }
----------------------------------------------------------
import java.util.*; //Class to represent a graph class Graph { int V;// No. of vertices //An Array of List which contains //references to the Adjacency List of //each vertex List
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started