What is the printed adjacency list after adding edges to an undirected graph with vertices 1, 2, 3?
use std::collections::HashMap;
fn main() {
let mut graph: HashMap<i32, Vec<i32>> = HashMap::new();
let edges = vec![(1, 2), (2, 3)];
for (u, v) in edges {
graph.entry(u).or_default().push(v);
graph.entry(v).or_default().push(u);
}
for (node, neighbors) in &graph {
print!("{} -> ", node);
for n in neighbors {
print!("{} ", n);
}
println!("null");
}
}Remember, undirected edges add neighbors both ways.
In an undirected graph, each edge connects two vertices both ways. So edge (1,2) adds 2 to 1's list and 1 to 2's list.
What is the printed adjacency list after adding edges to a directed weighted graph with vertices A, B, C?
use std::collections::HashMap;
fn main() {
let mut graph: HashMap<char, Vec<(char, i32)>> = HashMap::new();
let edges = vec![('A', 'B', 5), ('B', 'C', 3)];
for (u, v, w) in edges {
graph.entry(u).or_default().push((v, w));
}
for (node, neighbors) in &graph {
print!("{} -> ", node);
for (n, w) in neighbors {
print!("{}({}) ", n, w);
}
println!("null");
}
}Directed edges only add neighbors one way with weights.
Directed weighted edges add neighbors only from source to destination with weight shown.
Which graph type allows edges with direction and weights?
Think about edges that have arrows and numbers.
Directed weighted graphs have edges with direction (arrows) and weights (numbers).
What error occurs when running this Rust code for undirected graph edge insertion?
use std::collections::HashMap;
fn main() {
let mut graph: HashMap> = HashMap::new();
let edges = vec![(1, 2), (2, 3)];
for (u, v) in edges {
graph.entry(u).or_default().push(v);
graph.entry(v).or_default().push(u);
}
println!("{:?}", graph);
} Check line endings carefully in Rust.
Missing semicolon after push(u) causes syntax error in Rust.
Given edges with weights in an undirected graph, what is the total sum of all edge weights?
edges = vec![(1, 2, 4), (2, 3, 5), (3, 1, 6)];
Each edge weight counts once in undirected graph.
Sum weights 4 + 5 + 6 = 15. Do not double count edges.
