Skip to content
Merged
Show file tree
Hide file tree
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
4 changes: 1 addition & 3 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@

## TARGET

- [ ] Data Structure
- [ ] Algorithm
- [ ] DSA
- [ ] Design Pattern
- [ ] Problem Solving
- [ ] Complexity Analysis
- [ ] Advanced Concept
- [ ] Project
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ cargo test --bin huffman
cargo run --bin binary_search
```

3. [Depth First Search (DFS)]
4. [Breadth First Search (BFS)]
3. [Jump Search]
4. [Interpolation Search]

#### [1.2.2. Sorting](crates/dsa/src/algorithms/sorting/)

Expand Down Expand Up @@ -188,7 +188,16 @@ cargo test --bin huffman
6. [Bellman-Ford Algorithm]
7. [Floyd-Warshall Algorithm]
8. [Topological Sort]
9. [A* Search Algorithm]
9. [Depth First Search (DFS)](crates/dsa/src/algorithms/greedy/dfs.rs)

An example of a package manager to resolve and install dependencies using DFS approach.

```sh
cargo run --bin dfs
```

10. [Breadth First Search (BFS)]
11. [A* Search Algorithm]

#### [1.2.4. Miscellaneous Algorithms](crates/dsa/src/algorithms/misc/)

Expand Down
4 changes: 4 additions & 0 deletions crates/dsa/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ path = "src/algorithms/greedy/huffman_coding.rs"
name = "kruskal"
path = "src/algorithms/greedy/kruskal.rs"

[[bin]]
name = "dfs"
path = "src/algorithms/greedy/dfs.rs"

# Miscellaneous

[[bin]]
Expand Down
178 changes: 178 additions & 0 deletions crates/dsa/src/algorithms/greedy/dfs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
//! # Depth First Search Algorithm
//!
//! Depth first search algorithm is a graph searching algorithm that starts at
//! the root node and explores as far as possible to find out whether the node
//! exists in the tree.
//!
//!
//! some example of DFS implementation are as follows:
//!
//! 1. dependency resolution
//! 2. topological sorting
//! 3. maze generation, etc.
//!
//!
//! References:
//!
//! <https://en.wikipedia.org/wiki/Depth-first_search>
//! <https://www.geeksforgeeks.org/dsa/depth-first-search-or-dfs-for-a-graph/>
//!
//!
//! The following example shows the dependency resolution using DFS.
//! In this example, a Package will behave as a Node, and its dependencies will
//! behave as its children nodes.
//!
//! example:
//!
//! app -> [web, auth]
//! web -> [http, logger, db]
//! auth -> [crypto, db]
//! db -> [os]
//! crypto -> [os]
//! logger -> [os]
//! os -> []
//! ...
//!
//!
//! Which will look something like this
//! ```text
//! App
//! / \
//! / \
//! web auth
//! / \ \ | \
//! http logger db crypto
//! \ | / /
//! \ | / /
//! OS
//! ...
//!
//! ```

use std::collections::{HashMap, HashSet};

#[derive(Clone, Debug)]
struct Package {
id: String,
deps: Vec<String>, // dependencies
}

#[derive(Debug)]
struct Registry {
installed: HashSet<String>,
packages: HashMap<String, Package>,
}

impl Package {
fn new(id: String, deps: Vec<String>) -> Self {
Self { id, deps }
}
}

impl Registry {
fn new() -> Self {
Self {
installed: HashSet::new(),
packages: HashMap::new(),
}
}
fn insert(&mut self, pkg: Package) {
self.packages.insert(pkg.id.clone(), pkg);
}

fn depth_first_search(
&self,
id: String,
visiting: &mut HashSet<String>,
resolved: &mut HashSet<String>,
output: &mut Vec<String>,
) -> Result<(), String> {
if resolved.contains(&id) {
return Ok(());
}

// if a depends on b, and b depends on a, then we have a circular dependency
if visiting.contains(&id) {
return Err(format!("circular dependency detected at package {}", id));
}

visiting.insert(id.clone());

let pkg = self
.packages
.get(&id)
.ok_or_else(|| format!("package {} not found in registry", id))?;

for dep in &pkg.deps {
self.depth_first_search(dep.clone(), visiting, resolved, output)?;
}

visiting.remove(&id);
resolved.insert(id.clone());
output.push(id);

Ok(())
}

fn resolve(&self, id: String) -> Result<Vec<String>, String> {
// resolve packages
let mut visiting = HashSet::new();
let mut resolved = HashSet::new();
let mut output = Vec::new();
self.depth_first_search(id, &mut visiting, &mut resolved, &mut output)?;

Ok(output)
}

fn install(&mut self, id: String) -> Result<(), String> {
println!("{}", "-".repeat(40));
if self.installed.contains(&id) {
println!("Package \"{}\" is already installed", id);
return Ok(());
} else {
println!("Installing package \"{}\"", id);
}
let deps = self.resolve(id.clone())?;
println!("DFS Graph: {:?}", deps);

// install sub dependencies first, and ignore self dependency from dfs
for dep in deps.iter().filter(|&dep| dep != &id) {
self.install(dep.to_owned())?
}
self.installed.insert(id.clone());
println!("Package \"{}\" installed successfully", id);
Ok(())
}
}

fn main() {
println!("Depth first search algorithm");

let mut registry = Registry::new();

// build a graph of packages and their dependencies (similar to a lockfile)
registry.insert(Package::new("os".to_owned(), vec![]));
registry.insert(Package::new("http".to_owned(), vec!["os".to_owned()]));
registry.insert(Package::new("crypto".to_owned(), vec!["os".to_owned()]));
registry.insert(Package::new("db".to_owned(), vec!["os".to_owned()]));
registry.insert(Package::new("logger".to_owned(), vec!["os".to_owned()]));

// install higher level packages which will resolve the dependencies before installing
registry.insert(Package::new(
"web".to_owned(),
vec!["http".to_owned(), "logger".to_owned()],
));
registry.insert(Package::new(
"auth".to_owned(),
vec!["db".to_owned(), "crypto".to_owned()],
));

// insert app package which depends on web and auth
registry.insert(Package::new(
"app".to_owned(),
vec!["web".to_owned(), "auth".to_owned()],
));

// install package app
registry.install("app".to_owned()).unwrap();
}