diff --git a/src/graph/directed_graph.rs b/src/graph/directed_graph.rs index 8c76610..653e164 100644 --- a/src/graph/directed_graph.rs +++ b/src/graph/directed_graph.rs @@ -137,33 +137,26 @@ impl DirectedGraph { pub fn dfs_recursive( &self, start: VertexIndex, - visited_set: &mut HashSet, - dfs_order: &mut Vec, + visited: &mut HashSet, + order: &mut Vec, ) -> Result, GraphError> { - // Check if the starting vertex exists in the graph - if self.vertices.get(start).is_none() { - return Err(GraphError::VertexNotFound); - } + // Ensure the starting vertex exists + let vertex = self.vertices.get(start).ok_or(GraphError::VertexNotFound)?; // Mark the current vertex as visited - visited_set.insert(start); + visited.insert(start); - // Recurse for each unvisited neighbor - for neighbor in self - .vertices - .get(start) - .unwrap() - .borrow() - .outgoing_edges - .iter() - { - if !visited_set.contains(&neighbor.borrow().index) { - self.dfs_recursive(neighbor.borrow().index, visited_set, dfs_order)?; + // Recurse for unvisited neighbors + for neighbor in &vertex.borrow().outgoing_edges { + let neighbor_index = neighbor.borrow().index; + if !visited.contains(&neighbor_index) { + self.dfs_recursive(neighbor_index, visited, order)?; } } - dfs_order.push(start); - Ok(dfs_order.to_vec()) + // Record the vertex in the DFS order + order.push(start); + Ok(order.clone()) } // /// TopoSort Pseudocode diff --git a/src/graph/undirected_graph.rs b/src/graph/undirected_graph.rs index b1c2e98..74a8dfe 100644 --- a/src/graph/undirected_graph.rs +++ b/src/graph/undirected_graph.rs @@ -121,29 +121,31 @@ impl UndirectedGraph { /// mark w as explored /// add w to the end of Q pub fn shortest_path_bfs(&self, start: usize) -> Result, GraphError> { + // Ensure the starting vertex exists if !self.vertices.contains_key(&start) { return Err(GraphError::VertexNotFound); } - let mut dist = HashMap::new(); + + let mut distances = HashMap::new(); let mut queue = VecDeque::new(); - // Start by setting the distance to the start node as 0 - dist.insert(start, 0); + // Initialize the BFS + distances.insert(start, 0); queue.push_back(start); while let Some(current) = queue.pop_front() { - let current_distance = dist[¤t]; + let current_distance = distances[¤t]; for neighbor in self.get_neighbors(current) { - // If the neighbor hasn't been visited (i.e., it has no distance assigned) - if let std::collections::hash_map::Entry::Vacant(e) = dist.entry(neighbor) { - e.insert(current_distance + 1); + // Add unvisited neighbors to the queue + distances.entry(neighbor).or_insert_with(|| { queue.push_back(neighbor); - } + current_distance + 1 + }); } } - Ok(dist) + Ok(distances) } /// Pseudocode undirect connected components