|
| 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