22 graph
33 This problem requires you to implement a basic graph functio
44*/
5- // I AM NOT DONE
65
76use std:: collections:: { HashMap , HashSet } ;
87use std:: fmt;
@@ -30,6 +29,21 @@ impl Graph for UndirectedGraph {
3029 }
3130 fn add_edge ( & mut self , edge : ( & str , & str , i32 ) ) {
3231 //TODO
32+ let ( from, to, weight) = edge;
33+ // add nodes if missing
34+ self . adjacency_table
35+ . entry ( from. to_string ( ) )
36+ . or_insert_with ( Vec :: new) ;
37+ self . adjacency_table
38+ . entry ( to. to_string ( ) )
39+ . or_insert_with ( Vec :: new) ;
40+ // push both directions (undirected)
41+ if let Some ( neighs) = self . adjacency_table . get_mut ( from) {
42+ neighs. push ( ( to. to_string ( ) , weight) ) ;
43+ }
44+ if let Some ( neighs) = self . adjacency_table . get_mut ( to) {
45+ neighs. push ( ( from. to_string ( ) , weight) ) ;
46+ }
3347 }
3448}
3549pub trait Graph {
@@ -38,10 +52,17 @@ pub trait Graph {
3852 fn adjacency_table ( & self ) -> & HashMap < String , Vec < ( String , i32 ) > > ;
3953 fn add_node ( & mut self , node : & str ) -> bool {
4054 //TODO
41- true
55+ if self . adjacency_table ( ) . get ( node) . is_some ( ) {
56+ false
57+ } else {
58+ self . adjacency_table_mutable ( )
59+ . insert ( node. to_string ( ) , Vec :: new ( ) ) ;
60+ true
61+ }
4262 }
4363 fn add_edge ( & mut self , edge : ( & str , & str , i32 ) ) {
4464 //TODO
65+ let _ = edge;
4566 }
4667 fn contains ( & self , node : & str ) -> bool {
4768 self . adjacency_table ( ) . get ( node) . is_some ( )
0 commit comments