Graphs
Build a Graph as an Adjacency List
Represent an undirected graph as a per-vertex list of neighbours. For every
edge (u, v), append v to adj[u] and u to adj[v]. Neighbour lists
keep insertion order so the graph is a stable, deterministic fixture for the
search lessons.
Algorithm
Basic Implementation
basic.rs
use std::collections::BTreeMap;
fn main() {
let edges = [(1, 2), (1, 3), (2, 4), (3, 4), (4, 5), (5, 6)];
let mut adj: BTreeMap<i32, Vec<i32>> = BTreeMap::new();
for &(u, v) in edges.iter() {
adj.entry(u).or_insert_with(Vec::new).push(v);
adj.entry(v).or_insert_with(Vec::new).push(u);
}
let mut parts: Vec<String> = Vec::new();
for (v, nbrs) in &adj {
let items: Vec<String> = nbrs.iter().map(|n| n.to_string()).collect();
parts.push(format!("{}: [{}]", v, items.join(", ")));
}
println!("{{{}}}", parts.join(", "));
}
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
- Rust: a
BTreeMap<i32, Vec<i32>>keeps vertices sorted;entry().or_insert_withappends neighbours in edge order. - The replay shows the adjacency list after each edge is added, matching the lesson spec.
adjacency list
Each edge adds two directed entries, one in each direction.