diff --git a/src/graph.rs b/src/graph.rs index 903a358..7bd29fe 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -1,5 +1,5 @@ -use std::rc::Rc; use std::collections::VecDeque; +use std::rc::Rc; const MAXV: usize = 1000; @@ -15,12 +15,12 @@ struct Edgenode { pub struct Graph { edges: Vec>>, // adjacency info degree: Vec, // outdegree of each vertex - nvertices: usize, // number of vertices in graph + nvertices: usize, // number of vertices in graph nedges: i32, // number of edges in graph directed: bool, // is the graph directed? } -struct BfsState { +struct SearchState { // A vertex is `discovered` the first time we visit it. discovered: Vec, // A vertex is `processed` after we have traversed all outgoing @@ -57,7 +57,7 @@ impl Graph { } pub fn print_graph(&self) { - for i in 0..self.nvertices { + for i in 0..=self.nvertices { print!("{} -->", i); let mut p_opt = self.edges[i].clone(); while let Some(p) = p_opt { @@ -90,13 +90,12 @@ impl Graph { } pub fn bfs(&self, start: usize) { - let mut state = BfsState::new(); + let mut state = SearchState::new(); let mut q: VecDeque = VecDeque::new(); q.push_back(start); state.discovered[start] = true; while let Some(v) = q.pop_front() { - println!("process_vertex_early: {:?}", v); state.processed[v] = true; let mut p_opt = &self.edges[v]; while let Some(p) = p_opt { @@ -111,14 +110,37 @@ impl Graph { } p_opt = &p.next; } - println!("procesess vertex late: {:?}", v); + } + } + + pub fn dfs(&self, start: usize) { + let mut state = SearchState::new(); + let mut q: Vec = Vec::new(); + q.push(start); + state.discovered[start] = true; + + while let Some(v) = q.pop() { + let mut p_opt = &self.edges[v]; + while let Some(p) = p_opt { + let y: usize = p.y.try_into().unwrap(); + if !state.discovered[y] { + state.discovered[y] = true; + state.parent[y] = v.try_into().unwrap(); + q.push(y); + println!("process edge ({:?},{:?})", v, y); + } else if !state.processed[y] || self.directed { + println!("process edge ({:?},{:?})", v, y); + } + p_opt = &p.next; + } + state.processed[v] = true; } } } -impl BfsState { +impl SearchState { pub fn new() -> Self { - BfsState { + SearchState { discovered: vec![false; MAXV], processed: vec![false; MAXV], parent: vec![-1; MAXV], diff --git a/src/main.rs b/src/main.rs index 69d1777..89872c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,5 +22,8 @@ fn main() { graph.read_graph(data.to_string()); graph.print_graph(); + println!("running bfs"); graph.bfs(1); + println!("running dfs"); + graph.dfs(1); }