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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use std::hash::Hash;
use std::collections;
use crate::DirectedGraph;
use crate::Neighbors;
struct NodeState<G: DirectedGraph> {
node: G::Node,
neighbors: Neighbors<G>,
}
impl<'a, G: DirectedGraph+'a> NodeState<G> {
fn new(g: &'a G, node: <G as DirectedGraph>::Node) -> Self {
NodeState {
node: node.clone(), neighbors: g.neighbors(node),
}
}
}
pub struct BreadthFirstSearch<'a, G>
where
G: DirectedGraph,
<G as DirectedGraph>::Node: Eq+Hash,
{
graph: &'a G,
visited: collections::HashSet<<G as DirectedGraph>::Node>,
queue: collections::VecDeque<NodeState<G>>,
}
impl<'a, G> BreadthFirstSearch<'a, G>
where
G: 'a+DirectedGraph,
<G as DirectedGraph>::Node: Eq+Hash,
{
pub fn new(graph: &'a G) -> BreadthFirstSearch<'a, G> {
BreadthFirstSearch {
graph,
visited: collections::HashSet::new(),
queue: collections::VecDeque::new(),
}
}
pub fn search_from(&mut self, node: <G as DirectedGraph>::Node) {
self.queue.push_back(NodeState::new(self.graph, node));
}
}
impl<'a, G> Iterator for BreadthFirstSearch<'a, G>
where
G: 'a+DirectedGraph,
<G as DirectedGraph>::Node: Eq+Hash,
{
type Item = <G as DirectedGraph>::Node;
fn next(&mut self) -> Option<Self::Item> {
let next = 'outer: loop {
if self.queue.is_empty() {
return None;
}
{
let state = &mut self.queue.front_mut().unwrap();
if ! self.visited.contains(&state.node) {
self.visited.insert(state.node.clone());
return Some(state.node.clone());
}
while let Some(to) = state.neighbors.next() {
if ! self.visited.contains(&to) {
break 'outer to;
}
}
}
self.queue.pop_front();
};
self.visited.insert(next.clone());
self.queue.push_back(NodeState::new(self.graph, next.clone()));
Some(next)
}
}