Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dfs): make DFS more efficient by using IndexMap rather than Vec #553

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/directed/dfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::collections::HashSet;
use std::hash::Hash;
use std::iter::FusedIterator;

use crate::FxIndexSet;

/// Compute a path using the [depth-first search
/// algorithm](https://en.wikipedia.org/wiki/Depth-first_search).
///
Expand Down Expand Up @@ -46,18 +48,19 @@ use std::iter::FusedIterator;
/// ```
pub fn dfs<N, FN, IN, FS>(start: N, mut successors: FN, mut success: FS) -> Option<Vec<N>>
where
N: Eq,
N: Eq + Hash,
FN: FnMut(&N) -> IN,
IN: IntoIterator<Item = N>,
FS: FnMut(&N) -> bool,
{
let mut path = vec![start];
step(&mut path, &mut successors, &mut success).then_some(path)
let mut path = FxIndexSet::default();
path.insert(start);
step(&mut path, &mut successors, &mut success).then_some(Vec::from_iter(path))
}

fn step<N, FN, IN, FS>(path: &mut Vec<N>, successors: &mut FN, success: &mut FS) -> bool
fn step<N, FN, IN, FS>(path: &mut FxIndexSet<N>, successors: &mut FN, success: &mut FS) -> bool
where
N: Eq,
N: Eq + Hash,
FN: FnMut(&N) -> IN,
IN: IntoIterator<Item = N>,
FS: FnMut(&N) -> bool,
Expand All @@ -68,7 +71,7 @@ where
let successors_it = successors(path.last().unwrap());
for n in successors_it {
if !path.contains(&n) {
path.push(n);
path.insert(n);
if step(path, successors, success) {
return true;
}
Expand Down
Loading