Complete the code to check if a graph has cycles.
fn has_cycle(graph: &Vec<Vec<usize>>) -> bool {
let mut visited = vec![false; graph.len()];
for node in 0..graph.len() {
if !visited[node] && dfs(node, graph, &mut visited, [1]) {
return true;
}
}
false
}
fn dfs(node: usize, graph: &Vec<Vec<usize>>, visited: &mut Vec<bool>, parent: usize) -> bool {
visited[node] = true;
for &neighbor in &graph[node] {
if !visited[neighbor] {
if dfs(neighbor, graph, visited, node) {
return true;
}
} else if neighbor != parent {
return true;
}
}
false
}The initial parent value should be a value that cannot be a valid node index, such as usize::MAX, to indicate no parent at the start.
Complete the code to add an edge in an undirected graph.
fn add_edge(graph: &mut Vec<Vec<usize>>, u: usize, v: usize) {
graph[u].push([1]);
graph[v].push(u);
}To add an undirected edge, add v to u's adjacency list and u to v's list.
Fix the error in the code that checks if a tree is connected.
fn is_connected(graph: &Vec<Vec<usize>>) -> bool {
let mut visited = vec![false; graph.len()];
dfs(0, graph, &mut visited);
visited.iter().[1](|&v| v)
}
fn dfs(node: usize, graph: &Vec<Vec<usize>>, visited: &mut Vec<bool>) {
visited[node] = true;
for &neighbor in &graph[node] {
if !visited[neighbor] {
dfs(neighbor, graph, visited);
}
}
}To check if all nodes are visited, use all to confirm every element is true.
Fill both blanks to create a function that counts edges in an undirected graph.
fn count_edges(graph: &Vec<Vec<usize>>) -> usize {
let mut count = 0;
for neighbors in graph.iter() {
count += neighbors.[1]();
}
count [2] 2
}Count edges by summing lengths of adjacency lists, then divide by 2 because each edge is counted twice.
Fill all three blanks to create a function that builds a tree from edges and checks if it has cycles.
fn build_tree_and_check_cycle(n: usize, edges: &Vec<(usize, usize)>) -> bool {
let mut graph = vec![Vec::new(); n];
for &(u, v) in edges {
graph[u].push([1]);
graph[v].push([2]);
}
let mut visited = vec![false; n];
for node in 0..n {
if !visited[node] && dfs(node, &graph, &mut visited, [3]) {
return true;
}
}
false
}
fn dfs(node: usize, graph: &Vec<Vec<usize>>, visited: &mut Vec<bool>, parent: usize) -> bool {
visited[node] = true;
for &neighbor in &graph[node] {
if !visited[neighbor] {
if dfs(neighbor, graph, visited, node) {
return true;
}
} else if neighbor != parent {
return true;
}
}
false
}When building the graph, add v to u's list and u to v's list. For DFS, start with usize::MAX as no parent.
