Added basic graph implementation.

master
Tomasz Polgrabia 2025-03-01 19:34:35 +01:00
parent 7ce5794535
commit 6d75345c8f
2 changed files with 56 additions and 6 deletions

View File

@ -0,0 +1,38 @@
use std::iter::Map;
use std::collections::HashMap;
pub struct Vertex {
id: usize,
name: String
}
pub struct Graph {
vertices: HashMap<usize, Vertex>,
edges: HashMap<usize, Vec<usize>>
}
impl Graph {
pub fn new() -> Self {
return Graph { vertices: HashMap::new(), edges: HashMap::new() }
}
pub fn add_node(&mut self, vid: usize, name: String) {
let v = Vertex { id: vid, name: name };
self.vertices.insert(vid, v);
}
pub fn connect(&mut self, i: usize, j: usize) {
let res = self.edges.get_mut(&i);
match res {
Some(l) => {
l.push(j)
},
None => {}
}
}
pub fn DFS(&self, i: usize, j: usize) {
}
}

View File

@ -1,7 +1,11 @@
use std::cell::RefCell; // use std::cell::RefCell;
use std::rc::Rc; // use std::rc::Rc;
mod graph;
use graph::Graph;
// use std::collections::HashMap;
// use std::iter::Map;
// use std::borrow::BorrowMut; // use std::borrow::BorrowMut;
/*
struct Vertex { struct Vertex {
name: String, name: String,
edges: RefCell<Vec<Vertex>> edges: RefCell<Vec<Vertex>>
@ -25,7 +29,7 @@ impl Graph {
} }
fn connect(&mut self, i: usize, j: usize) { fn connect(&mut self, i: usize, _j: usize) {
// let nodej = Rc::clone(&self.vertices[j]); // let nodej = Rc::clone(&self.vertices[j]);
// let nodei = Rc::clone(&self.vertices[i]); // let nodei = Rc::clone(&self.vertices[i]);
// nodei.into_inner(); // nodei.into_inner();
@ -36,13 +40,14 @@ impl Graph {
// let mut edges_new = self.vertices[i].edges.get_mut(); // let mut edges_new = self.vertices[i].edges.get_mut();
// let inner = self.vertices[j].take(); // let inner = self.vertices[j].take();
// self.vertices[i].get_mut().edges.borrow_mut().push(inner); // self.vertices[i].get_mut().edges.borrow_mut().push(inner);
let list = self.vertices[i].get_mut().edges.clone(); // let list = self.vertices[i].get_mut().edges.clone();
self.vertices[i].get_mut().edges.replace(vec![]); self.vertices[i].get_mut().edges.replace(vec![]);
} }
} }
*/
fn main() { fn main() {
/*
let mut g = Graph::new(); let mut g = Graph::new();
g.add_node(String::from("Vertice #1")); g.add_node(String::from("Vertice #1"));
g.add_node(String::from("Vertice #2")); g.add_node(String::from("Vertice #2"));
@ -52,4 +57,11 @@ fn main() {
g.connect(1, 2); g.connect(1, 2);
println!("Done, Vertices count: {}.", g.vertices_count()); println!("Done, Vertices count: {}.", g.vertices_count());
*/
let mut g = Graph::new();
g.add_node(1, String::from("Node #1"));
g.add_node(2, String::from("Node #2"));
g.add_node(3, String::from("Node #3"));
g.connect(1,2);
g.connect(2,3);
} }