Complete the code to add the starting node to the queue in BFS.
let mut queue = VecDeque::new();
queue.[1](start_node);In BFS, we add nodes to the back of the queue to process them in order.
Complete the code to remove the current node from the queue in BFS.
while let Some(current) = queue.[1]() { // process current }
BFS removes nodes from the front of the queue to process them in FIFO order.
Fix the error in the code to mark neighbors as visited before adding to the queue.
for &neighbor in graph.get(¤t).unwrap_or(&Vec::new()).iter() { if !visited.contains(&neighbor) { visited.[1](neighbor); queue.push_back(neighbor); } }
We use insert to mark a neighbor as visited in a HashSet before adding it to the queue.
Fill both blanks to create a BFS function that returns the order of visited nodes.
fn bfs(graph: &HashMap<i32, Vec<i32>>, start: i32) -> Vec<i32> {
let mut visited = HashSet::new();
let mut queue = VecDeque::new();
let mut order = Vec::new();
visited.[1](start);
queue.[2](start);
while let Some(node) = queue.pop_front() {
order.push(node);
for &neighbor in graph.get(&node).unwrap_or(&Vec::new()).iter() {
if !visited.contains(&neighbor) {
visited.insert(neighbor);
queue.push_back(neighbor);
}
}
}
order
}We insert the start node into visited and push it to the back of the queue to begin BFS.
Fill all three blanks to complete BFS that uses a queue and visited set correctly.
fn bfs(graph: &HashMap<i32, Vec<i32>>, start: i32) -> Vec<i32> {
let mut visited = HashSet::new();
let mut queue = VecDeque::new();
let mut order = Vec::new();
visited.[1](start);
queue.[2](start);
while let Some(node) = queue.[3]() {
order.push(node);
for &neighbor in graph.get(&node).unwrap_or(&Vec::new()).iter() {
if !visited.contains(&neighbor) {
visited.insert(neighbor);
queue.push_back(neighbor);
}
}
}
order
}We insert the start node into visited, push it to the back of the queue, and pop nodes from the front to process BFS correctly.
