Complete the code to create a graph node with an adjacency list.
struct Node {
value: i32,
neighbors: Vec<[1]>,
}The neighbors field holds a list of adjacent nodes, so its type is Vec
Complete the code to add an edge between two nodes in an undirected graph.
fn add_edge(node1: &mut Node, node2: &mut Node) {
node1.neighbors.push([1]);
node2.neighbors.push(node1.clone());
}To add an edge, node1's neighbors should include node2, so push node2.clone().
Fix the error in the code to check if a graph contains a cycle.
fn has_cycle(node: &Node, visited: &mut Vec<bool>, parent: usize) -> bool {
visited[node.value as usize] = true;
for neighbor in &node.neighbors {
if !visited[neighbor.value as usize] {
if has_cycle(neighbor, visited, node.value as usize) [1] {
return true;
}
} else if neighbor.value as usize != parent {
return true;
}
}
false
}The recursive call returns a bool; checking if it is not false means a cycle was found.
Fill both blanks to create a graph adjacency list using a HashMap.
use std::collections::HashMap; let mut graph: HashMap<i32, Vec<i32>> = HashMap::new(); graph.entry([1]).or_insert(Vec::new()).push([2]);
We add an edge from node 1 to node 2 in the adjacency list.
Fill all three blanks to implement a BFS traversal starting from a node.
use std::collections::VecDeque;
fn bfs(start: i32, graph: &HashMap<i32, Vec<i32>>) {
let mut visited = std::collections::HashSet::new();
let mut queue = VecDeque::new();
queue.push_back([1]);
visited.insert([2]);
while let Some(node) = queue.pop_front() {
println!("Visited: {}", node);
if let Some(neighbors) = graph.get(&node) {
for &neighbor in neighbors {
if !visited.contains(&neighbor) {
queue.push_back(neighbor);
visited.insert([3]);
}
}
}
}
}Start BFS by pushing and marking the start node visited. Insert neighbors when discovered.
