Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start DFS from the given node.
DSA Rust
fn dfs(graph: &Vec<Vec<usize>>, node: usize, visited: &mut Vec<bool>) {
if visited[node] {
return;
}
visited[node] = true;
for &neighbor in &graph[node] {
dfs(graph, [1], visited);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling dfs on the current node again causes infinite recursion.
Using an index out of bounds instead of the neighbor.
✗ Incorrect
The DFS function should recursively call itself on each neighbor of the current node to explore the graph deeply.
2fill in blank
mediumComplete the code to mark the current node as visited.
DSA Rust
fn dfs(graph: &Vec<Vec<usize>>, node: usize, visited: &mut Vec<bool>) {
if visited[node] {
return;
}
visited[[1]] = true;
for &neighbor in &graph[node] {
dfs(graph, neighbor, visited);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Marking neighbors as visited before visiting them.
Using an incorrect index causing panic.
✗ Incorrect
We mark the current node as visited to avoid revisiting it and causing infinite loops.
3fill in blank
hardFix the error in the DFS function call to avoid infinite recursion.
DSA Rust
fn dfs(graph: &Vec<Vec<usize>>, node: usize, visited: &mut Vec<bool>) {
if visited[node] {
return;
}
visited[node] = true;
for &neighbor in &graph[node] {
dfs(graph, [1], visited); // Fix this line
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling dfs on the current node causes infinite recursion.
Using an invalid index causing panic.
✗ Incorrect
The recursive call should be on the neighbor node to explore new nodes, not the current node again.
4fill in blank
hardFill both blanks to create a DFS function that prints nodes in order of visit.
DSA Rust
fn dfs(graph: &Vec<Vec<usize>>, node: usize, visited: &mut Vec<bool>) {
if visited[node] {
return;
}
visited[node] = true;
println!("Visited: {}", [1]);
for &neighbor in &graph[[2]] {
dfs(graph, neighbor, visited);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Printing neighbor instead of current node.
Using wrong index to access neighbors.
✗ Incorrect
We print the current node and iterate over its neighbors to continue DFS.
5fill in blank
hardFill all three blanks to implement DFS that collects visited nodes in order.
DSA Rust
fn dfs_collect(graph: &Vec<Vec<usize>>, node: usize, visited: &mut Vec<bool>, result: &mut Vec<usize>) {
if visited[[1]] {
return;
}
visited[node] = true;
result.[2](node);
for &neighbor in &graph[[3]] {
dfs_collect(graph, neighbor, visited, result);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push to add nodes.
Checking visited status of wrong index.
Accessing neighbors with wrong index.
✗ Incorrect
We check if the current node is visited, mark it, add it to result using push, and explore neighbors.
