Skip to content

Commit 1ca1943

Browse files
04121644
1 parent e76dcdf commit 1ca1943

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

exercises/algorithm/algorithm5.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
/*
2-
bfs
3-
This problem requires you to implement a basic BFS algorithm
2+
bfs
3+
This problem requires you to implement a basic BFS algorithm
44
*/
55

66
//I AM NOT DONE
7+
78
use std::collections::VecDeque;
89

910
// Define a graph
1011
struct Graph {
11-
adj: Vec<Vec<usize>>,
12+
adj: Vec<Vec<usize>>,
1213
}
1314

1415
impl Graph {
@@ -21,21 +22,31 @@ impl Graph {
2122

2223
// Add an edge to the graph
2324
fn add_edge(&mut self, src: usize, dest: usize) {
24-
self.adj[src].push(dest);
25-
self.adj[dest].push(src);
25+
self.adj[src].push(dest);
26+
self.adj[dest].push(src);
2627
}
2728

2829
// Perform a breadth-first search on the graph, return the order of visited nodes
2930
fn bfs_with_return(&self, start: usize) -> Vec<usize> {
30-
31-
//TODO
32-
3331
let mut visit_order = vec![];
32+
let mut visited = vec![false; self.adj.len()];
33+
let mut queue = VecDeque::new();
34+
35+
queue.push_back(start);
36+
visited[start] = true;
37+
while let Some(node) = queue.pop_front() {
38+
visit_order.push(node);
39+
for &neighbor in &self.adj[node] {
40+
if !visited[neighbor] {
41+
visited[neighbor] = true;
42+
queue.push_back(neighbor);
43+
}
44+
}
45+
}
3446
visit_order
3547
}
3648
}
3749

38-
3950
#[cfg(test)]
4051
mod tests {
4152
use super::*;
@@ -84,4 +95,3 @@ mod tests {
8495
assert_eq!(visited_order, vec![0]);
8596
}
8697
}
87-

0 commit comments

Comments
 (0)