Menu

(explain this code please) class Graph { private int V; // No. of vertices , , , , , ,

(explain this code please)

class Graph
{
private int V; // No. of vertices
// Array of lists for Adjacency List Representation
private LinkedList<Integer> adj[];
// Constructor
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++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<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  //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() + ” “);
}
}

Expert Answer

Step 1/3
This is the code for topological sorting we use DFS(Depth First Search) for solving this question.
Firstly we are creating a class for Graph and declaring the no. of vertices and we are declaring a linked list to show the adjacency list for the particular graph.We are using a constructor to initialize the variables.
After that in the addEdge function we are just adding the edge to the adjacency list.Topological sort is nothing but the node should not contain any indegree means there should not be any edge coming from other node.To do this in the topologicalSortUtil function we are using the DFS.Firstly we are checking if the node is visited or not and after that we are checking for its adjacent nodes using a list iteratror. By doing that we are going to the last node recursively where it has no adjacents and after the recursion we are storing the element in the stack. So by doing this we will get the first node at the top of the stack beacuse it does not contain any indegree.

OR