Answered step by step
Verified Expert Solution
Question
1 Approved Answer
(explain this code please) class Graph { private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList adj[];
(explain this code please)
class Graph
{
private int V; // No. of vertices
// Array of lists for Adjacency List Representation
private LinkedList adj[];
// Constructor
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i=0; i
adj[i] = new LinkedList();
} //initialize the list with 0 values.
}
// 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;
// Recur for all the vertices adjacent to this vertex
Iterator 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 //push the element in stack after recursion ends.
stack.push(new Integer(v)); } // The function to do Topological Sort. It uses recursive //topological sort function call from here.
void topologicalSort() {
Stack stack = new Stack();
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() + " ");
}
}
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