Directed Graph
A type-safe, generic directed graph implementation for Rust
Installation
Add the following to the dependencies section of your Cargo.toml:
[]
= { = "./path-to-this-crate" } # For local development
# Or use the crates.io published version:
# directed_graph = "0.1.0"
Basic Usage
Graph Manipulation
use DirectedGraph;
// Initialize an empty directed graph with integer nodes
let mut graph = new;
// Add nodes with outgoing edges (duplicate edges are automatically ignored)
graph.add_node; // Node 1 -> 2, 1 -> 3
graph.add_node; // Node 2 -> 3
graph.add_node; // Append edge 1 -> 4 (3 is a duplicate and ignored)
graph.add_node; // Add an isolated node with no outgoing edges
// Check if a node exists in the graph
assert!;
assert!;
// Query the adjacent nodes (outgoing edges) of a given node
let adj_1 = graph.get_adjacent_nodes.unwrap;
assert!;
Retrieve Graph Statistics
// Count the unique nodes and edges in the graph
assert_eq!; // Nodes in graph: 1, 2, 3, 4
assert_eq!; // Edges in graph: 1->2, 1->3, 1->4, 2->3
Remove Nodes & Edges
// Remove a single directed edge (1 -> 3)
assert!; // Returns true (edge exists and is removed)
assert!; // Returns false (edge does not exist)
assert_eq!;
// Remove a node and all its outgoing edges from the graph
let removed_edges = graph.remove_node.unwrap;
assert_eq!; // Node 2 had one outgoing edge: 2->3
assert!; // Node 2 is no longer in the graph
assert_eq!;
Graph Analysis
See analyze module for more
use ;
// Create a cyclic directed graph
let mut cyclic_graph = new;
cyclic_graph.add_node;
cyclic_graph.add_node;
cyclic_graph.add_node;
// Run graph analysis
let result = analyze_digraph;
// Detect cycles in the graph
assert!;
assert!;
// Create an acyclic directed graph (DAG)
let mut dag = new;
dag.add_node;
dag.add_node;
let result = analyze_digraph;
assert!;
Using Custom Node Types (Not Recommended)
We recommend associating your node instances with a unique identifier (e.g., u64 or String). If you choose to use a custom node type regardless, refer to the test_custom_node() test case in the crate's test suite for implementation guidance.
You will need to manually implement the following Rust traits for your custom type:
EqPartialEqHashPartialOrdOrd
Algorithm
This implementation leverages classic cycle-detection algorithms for directed graphs, with core logic based on the following foundational works:
- Tarjan, R. (1973). Enumeration of the elementary circuits of a directed graph. SIAM Journal on Computing, 2(3), 211–216.
- Szwarcfiter, J. L., & Lauer, P. E. (1976). A search strategy for the elementary cycles of a directed graph. BIT Numerical Mathematics, 16(2), 192–204.
License
This project is licensed under the MIT License