Complete the code to declare the adjacency list for the graph.
List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < [1]; i++) { graph.add(new ArrayList<>()); }
The variable V usually represents the number of vertices in the graph. We create an adjacency list with V empty lists.
Complete the code to mark a node as visited in DFS.
void dfs(int node, boolean[] visited, List<List<Integer>> graph, Stack<Integer> stack) {
visited[[1]] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(neighbor, visited, graph, stack);
}
}
stack.push(node);
}We mark the current node as visited before exploring its neighbors.
Fix the error in the DFS call to correctly perform topological sort.
for (int i = 0; i < V; i++) { if (!visited[i]) { dfs([1], visited, graph, stack); } }
We call DFS on the current node i if it is not visited.
Fill both blanks to create the topological order list from the stack.
List<Integer> topoOrder = new ArrayList<>(); while (!stack.[1]()) { topoOrder.[2](stack.pop()); }
peek() instead of isEmpty() in the while condition.push() instead of add() on the list.We check if the stack is empty using isEmpty() and add elements to the list using add().
Fill all three blanks to complete the DFS method signature and call.
public void dfs([1] node, [2] visited, [3] graph, Stack<Integer> stack) { visited[node] = true; for (int neighbor : graph.get(node)) { if (!visited[neighbor]) { dfs(neighbor, visited, graph, stack); } } stack.push(node); }
The DFS method takes an integer node, a boolean array for visited nodes, and the graph as a list of lists.
