struct Vertex<V> {
value: V,
neighbours: Vec<Weak<RefCell<Vertex<V>>>>,
}
// ...
fn dft_helper(start: Rc<RefCell<Vertex<V>>>, f: &impl Fn(&V), s: &mut Vec<*const Vertex<V>>) {
s.push(start.as_ptr());
(f)(&start.borrow().value);
for n in &start.borrow().neighbours {
let n = n.upgrade().expect("Invalid neighbor");
if s.iter().all(|&p| p != n.as_ptr()) {
Self::dft_helper(n, f, s);
}
}
}
void dfs(Node& root, std::function<void(Node*)> f) {
std::stack<Node*> queue;
queue.push(&root);
std::unordered_set<const Node*> visited;
while (!queue.empty()) {
Node* const node = queue.top();
queue.pop();
f(node);
visited.insert(node);
for (Node* const neighbor : node->neighbors) {
if (visited.find(neighbor) == visited.end()) {
queue.push(neighbor);
}
}
}
}