Skip to content

Commit 741c11b

Browse files
authored
add rust breadth first search (#293)
1 parent add6033 commit 741c11b

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

06_breadth-first_search/rust/Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "breadth_first"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
use std::collections::{HashMap, VecDeque};
2+
use std::fmt;
3+
4+
#[derive(Eq, Hash, PartialEq)]
5+
struct Person(String);
6+
7+
impl Person {
8+
fn is_seller(&self) -> bool {
9+
self.0.ends_with('m')
10+
}
11+
}
12+
13+
impl fmt::Display for Person {
14+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15+
f.write_str(&self.0)
16+
}
17+
}
18+
19+
fn search(graph: &HashMap<&Person, Vec<&Person>>, start: &Person) {
20+
let mut search_queue = VecDeque::new();
21+
search_queue.push_back(start);
22+
23+
let mut searched: Vec<&Person> = Vec::with_capacity(graph.len());
24+
loop {
25+
match search_queue.pop_front() {
26+
Some(person) => {
27+
if !searched.contains(&person) {
28+
if person.is_seller() {
29+
println!("{} is a mango seller!", person);
30+
break;
31+
} else {
32+
for p in graph.get(&person).unwrap() {
33+
search_queue.push_back(p);
34+
searched.push(person);
35+
}
36+
}
37+
}
38+
}
39+
None => {
40+
println!("no mango seller found!");
41+
break;
42+
}
43+
}
44+
}
45+
}
46+
47+
fn main() {
48+
let you = Person("you".to_string());
49+
let alice = Person("alice".to_string());
50+
let bob = Person("bob".to_string());
51+
let claire = Person("claire".to_string());
52+
let anuj = Person("anuj".to_string());
53+
let peggy = Person("peggy".to_string());
54+
let thom = Person("thom".to_string());
55+
let jonny = Person("jonny".to_string());
56+
57+
let mut graph = HashMap::new();
58+
graph.insert(&you, vec![&alice, &bob, &claire]);
59+
graph.insert(&bob, vec![&anuj, &peggy]);
60+
graph.insert(&alice, vec![&peggy]);
61+
graph.insert(&claire, vec![&thom, &jonny]);
62+
graph.insert(&anuj, vec![]);
63+
graph.insert(&peggy, vec![]);
64+
graph.insert(&thom, vec![]);
65+
graph.insert(&jonny, vec![]);
66+
67+
search(&graph, &you);
68+
}

0 commit comments

Comments
 (0)