Complete the code to declare the adjacency list for the graph.
let graph: Vec<Vec<usize>> = [1];The adjacency list is a vector of vectors, each inner vector representing edges from a node. Using vec![vec![]; n] creates n empty vectors.
Complete the code to mark a node as visited in DFS.
visited[[1]] = true;In DFS, the current node is usually passed as node. Marking visited[node] as true means we have visited this node.
Fix the error in the DFS recursive call to visit neighbors.
for &neighbor in graph[[1]].iter() { if !visited[neighbor] { dfs(graph, neighbor, visited, stack); } }
We want to iterate over neighbors of the current node. So the index to access adjacency list is node.
Fill both blanks to push the node onto the stack after visiting neighbors.
stack.[1]([2]);
After visiting all neighbors, we push the current node onto the stack to record the topological order.
Fill all three blanks to create the topological sort function using DFS.
fn topological_sort(graph: &Vec<Vec<usize>>, n: usize) -> Vec<usize> {
let mut visited = vec![false; [1]];
let mut stack = Vec::new();
for node in 0..[2] {
if !visited[node] {
dfs(graph, node, &mut visited, &mut stack);
}
}
stack.[3]();
stack
}We initialize visited with size n. We loop from 0 to graph.len() to cover all nodes. Finally, we reverse the stack to get the correct topological order.
