diff --git a/README.md b/README.md index 8e9c5be..c7d262f 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,5 @@ cargo codspeed run -m walltime ``` Note: You can also set the `CODSPEED_RUNNER_MODE` environment variable to `walltime` to avoid passing `-m walltime` every time. + +Name: Mehdi diff --git a/src/bfs.rs b/src/bfs.rs index 487fddc..be20b7b 100644 --- a/src/bfs.rs +++ b/src/bfs.rs @@ -1,4 +1,7 @@ -use std::collections::HashSet; +use std::collections::{ + HashSet, + VecDeque +}; /// A simple graph represented as an adjacency list #[derive(Debug, Clone)] @@ -17,31 +20,36 @@ impl Graph { pub fn add_edge(&mut self, from: usize, to: usize) { self.adjacency[from].push(to); } - pub fn num_nodes(&self) -> usize { self.adjacency.len() } } -/// Naive BFS implementation using Vec as a queue (intentionally slow) +/// Naive BFS implementation using VecDeque /// Returns the order in which nodes were visited pub fn bfs_naive(graph: &Graph, start: usize) -> Vec { - let mut visited = HashSet::new(); - let mut queue = Vec::new(); // Using Vec instead of VecDeque - intentionally inefficient! - let mut result = Vec::new(); + let n_nodes = graph.num_nodes(); + + let mut visited = HashSet::with_capacity(n_nodes); + let mut queue = VecDeque::with_capacity(n_nodes); + let mut result = Vec::with_capacity(n_nodes); - queue.push(start); + queue.push_back(start); visited.insert(start); while !queue.is_empty() { - // remove(0) is O(n) - this makes BFS slow! - let node = queue.remove(0); + let node = queue + .pop_front() + .expect( + "This used to be a remove(0), so I assume underlying value exists" + ) + ; result.push(node); if let Some(neighbors) = graph.adjacency.get(node) { for &neighbor in neighbors { if visited.insert(neighbor) { - queue.push(neighbor); + queue.push_back(neighbor); } } }