diff --git a/src/graph.rs b/src/graph.rs index 7bd29fe..010804c 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -8,7 +8,7 @@ struct Edgenode { #[allow(unused)] weight: i32, // Edge weight, if any - y: i32, // Adjacency info + y: usize, // Adjacency info next: Option>, // next edge in list } @@ -16,7 +16,7 @@ pub struct Graph { edges: Vec>>, // adjacency info degree: Vec, // outdegree of each vertex nvertices: usize, // number of vertices in graph - nedges: i32, // number of edges in graph + nedges: usize, // number of edges in graph directed: bool, // is the graph directed? } @@ -26,8 +26,10 @@ struct SearchState { // A vertex is `processed` after we have traversed all outgoing // edges from it. processed: Vec, - // Discovery relation + // Discovery relation. Needs to be signed cause we initialize it to -1 parent: Vec, + // Time tracking for DFS + time: usize, } impl Graph { @@ -41,7 +43,7 @@ impl Graph { } } - fn insert_edge(&mut self, x: usize, y: i32, directed: bool) { + fn insert_edge(&mut self, x: usize, y: usize, directed: bool) { let p = Rc::new(Edgenode { y, weight: 0, @@ -52,7 +54,7 @@ impl Graph { if directed { self.nedges += 1; } else { - self.insert_edge(y.try_into().unwrap(), x.try_into().unwrap(), true); + self.insert_edge(y, x, true); } } @@ -83,9 +85,9 @@ impl Graph { // After that, parse edges as (x, y) for _ in 0..num_edges { - let x: i32 = data_parsed.pop().unwrap().parse().unwrap(); - let y: i32 = data_parsed.pop().unwrap().parse().unwrap(); - self.insert_edge(x.try_into().unwrap(), y, directed); + let x: usize = data_parsed.pop().unwrap().parse().unwrap(); + let y: usize = data_parsed.pop().unwrap().parse().unwrap(); + self.insert_edge(x, y, directed); } } @@ -99,7 +101,7 @@ impl Graph { state.processed[v] = true; let mut p_opt = &self.edges[v]; while let Some(p) = p_opt { - let y: usize = p.y.try_into().unwrap(); + let y: usize = p.y; if !state.processed[y] || self.directed { println!("process edge ({:?},{:?})", v, y); } @@ -122,7 +124,7 @@ impl Graph { 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(); + let y: usize = p.y; if !state.discovered[y] { state.discovered[y] = true; state.parent[y] = v.try_into().unwrap(); @@ -131,6 +133,9 @@ impl Graph { } else if !state.processed[y] || self.directed { println!("process edge ({:?},{:?})", v, y); } + if state.parent[y] != v.try_into().unwrap() { + println!("cycle from {:?} to {:?}", v, y); + } p_opt = &p.next; } state.processed[v] = true; @@ -144,6 +149,7 @@ impl SearchState { discovered: vec![false; MAXV], processed: vec![false; MAXV], parent: vec![-1; MAXV], + time: 0, } } }