use std::collections::HashMap;
// Graph using adjacency list
struct GraphList {
adj_list: HashMap<usize, Vec<usize>>,
}
impl GraphList {
fn new() -> Self {
GraphList { adj_list: HashMap::new() }
}
fn add_edge(&mut self, u: usize, v: usize) {
self.adj_list.entry(u).or_default().push(v);
self.adj_list.entry(v).or_default().push(u);
}
fn neighbors(&self, u: usize) -> Vec<usize> {
self.adj_list.get(&u).cloned().unwrap_or_default()
}
fn print(&self) {
for (node, neighbors) in &self.adj_list {
print!("City {} -> [", node);
for (i, n) in neighbors.iter().enumerate() {
if i > 0 { print!(", "); }
print!("{}", n);
}
println!("]");
}
}
}
// Graph using adjacency matrix
struct GraphMatrix {
matrix: Vec<Vec<u8>>,
size: usize,
}
impl GraphMatrix {
fn new(size: usize) -> Self {
GraphMatrix {
matrix: vec![vec![0; size]; size],
size,
}
}
fn add_edge(&mut self, u: usize, v: usize) {
self.matrix[u - 1][v - 1] = 1;
self.matrix[v - 1][u - 1] = 1;
}
fn connected(&self, u: usize, v: usize) -> bool {
self.matrix[u - 1][v - 1] == 1
}
fn print(&self) {
print!(" ");
for i in 1..=self.size {
print!("{} ", i);
}
println!();
for i in 0..self.size {
print!("{} [ ", i + 1);
for j in 0..self.size {
print!("{} ", self.matrix[i][j]);
}
println!("]");
}
}
}
fn main() {
// Build graph with 3 cities
let mut graph_list = GraphList::new();
graph_list.add_edge(1, 2);
graph_list.add_edge(1, 3);
let mut graph_matrix = GraphMatrix::new(3);
graph_matrix.add_edge(1, 2);
graph_matrix.add_edge(1, 3);
println!("Adjacency List:");
graph_list.print();
println!("\nAdjacency Matrix:");
graph_matrix.print();
// Check connection between city 2 and 3
println!("\nCheck if city 2 connects to city 3:");
println!("List: {:?}", graph_list.neighbors(2));
println!("Matrix: {}", graph_matrix.connected(2, 3));
}self.adj_list.entry(u).or_default().push(v);
Add neighbor v to u's adjacency list
self.adj_list.entry(v).or_default().push(u);
Add neighbor u to v's adjacency list for undirected graph
self.matrix[u - 1][v - 1] = 1;
Mark edge from u to v in matrix
self.matrix[v - 1][u - 1] = 1;
Mark edge from v to u in matrix for undirected graph
self.adj_list.get(&u).cloned().unwrap_or_default()
Retrieve neighbors of u or empty if none
self.matrix[u - 1][v - 1] == 1
Check if edge exists between u and v
Adjacency List:
City 1 -> [2, 3]
City 2 -> [1]
City 3 -> [1]
Adjacency Matrix:
1 2 3
1 [ 0 1 1 ]
2 [ 1 0 0 ]
3 [ 1 0 0 ]
Check if city 2 connects to city 3:
List: [1]
Matrix: false