Implement the graph data structure
Rust Programming Language
Problem
Rust program that implements a graph data structure using an adjacency list
Input
use std::collections::HashMap;struct Graph {vertices: HashMap<i32, Vec<i32>>}impl Graph {fn new() -> Self {Self { vertices: HashMap::new() }}fn add_vertex(&mut self, vertex: i32) {self.vertices.entry(vertex).or_insert(Vec::new());}fn add_edge(&mut self, src: i32, dest: i32) {self.vertices.entry(src).or_insert(Vec::new()).push(dest);self.vertices.entry(dest).or_insert(Vec::new()).push(src);}fn print(&self) {for (vertex, neighbors) in &self.vertices {print!("{}: ", vertex);for neighbor in neighbors {print!("{} ", neighbor);}println!();}}}fn main() {let mut g = Graph::new();g.add_vertex(0);g.add_vertex(1);g.add_vertex(2);g.add_vertex(3);g.add_edge(0, 1);g.add_edge(1, 2);g.add_edge(2, 3);g.add_edge(3, 0);g.print();}{codeBox}
Output
0: 1 31: 0 22: 1 33: 2 0{codeBox}
Explanation
In this implementation, the Graph struct contains a HashMap where the keys are vertices represented by i32 integers, and the values are vectors of adjacent vertices. The add_vertex method simply adds a new vertex to the graph, while the add_edge method adds an undirected edge between two vertices by appending each vertex to the other's list of adjacent vertices. Finally, the print method prints out the contents of the graph, one vertex and its neighbors per line.
The main function demonstrates the use of the graph by creating a simple four-node cycle and printing it out. This program can be easily modified to suit different graph representations or algorithms.