-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathbfs.rs
47 lines (45 loc) · 1.28 KB
/
bfs.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#![allow(clippy::many_single_char_names,clippy::explicit_counter_loop, clippy::redundant_closure)]
use super::adjacencylists::AdjacencyLists;
use chapter01::interface::{Graph, Queue};
use chapter03::sllist::SLList;
pub fn bfs(g: &AdjacencyLists, r: usize) {
let mut seen = vec![false; g.nvertices()];
let mut q = SLList::new();
q.add(r);
if let Some(e) = seen.get_mut(r) {
*e = true
}
while let Some(i) = q.remove() {
let edges = g.out_edges(i);
for j in edges.into_iter() {
if !seen[j] {
q.add(j);
if let Some(e) = seen.get_mut(j) {
*e = true
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use rand::{thread_rng, Rng};
use std::collections::HashSet;
#[test]
fn test_bfs() {
let n = 50;
let mut adjm = AdjacencyLists::new(n);
let mut set: HashSet<(usize, usize)> = HashSet::new();
let mut rng = thread_rng();
for _ in 0..(5 * n) {
let (i, j) = (rng.gen_range(0, n), rng.gen_range(0, n));
if !set.contains(&(i, j)) {
set.insert((i, j));
adjm.add_edge(i, j);
}
}
bfs(&adjm, 0);
println!("done");
}
}