use std::collections::{HashMap, HashSet};
use std::hash::Hash;
pub fn is_acyclic<N: Eq + Hash + Copy>(edges: &HashSet<(N, N)>) -> bool {
find_cycle(edges).is_none()
}
pub fn find_cycle<N: Eq + Hash + Copy>(edges: &HashSet<(N, N)>) -> Option<Vec<N>> {
let mut adj: HashMap<N, Vec<N>> = HashMap::new();
for &(from, to) in edges {
adj.entry(from).or_default().push(to);
}
let nodes: Vec<N> = adj.keys().copied().collect();
let mut visited: HashSet<N> = HashSet::new();
let mut on_stack: HashSet<N> = HashSet::new();
let mut path: Vec<N> = Vec::new();
for start in nodes {
if visited.contains(&start) {
continue;
}
let mut stack: Vec<(N, usize)> = vec![(start, 0)];
on_stack.insert(start);
path.push(start);
while let Some((node, idx)) = stack.last_mut() {
let node = *node;
let neighbors = adj.get(&node).map(Vec::as_slice).unwrap_or(&[]);
if *idx < neighbors.len() {
let next = neighbors[*idx];
*idx += 1;
if on_stack.contains(&next) {
let cycle_start = path.iter().position(|&n| n == next).unwrap();
return Some(path[cycle_start..].to_vec());
}
if !visited.contains(&next) {
on_stack.insert(next);
path.push(next);
stack.push((next, 0));
}
} else {
visited.insert(node);
on_stack.remove(&node);
path.pop();
stack.pop();
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn edges(pairs: &[(u64, u64)]) -> HashSet<(u64, u64)> {
pairs.iter().copied().collect()
}
#[test]
fn acyclic_empty() {
assert!(is_acyclic::<u64>(&HashSet::new()));
}
#[test]
fn acyclic_single_edge() {
assert!(is_acyclic(&edges(&[(0, 1)])));
}
#[test]
fn acyclic_line() {
assert!(is_acyclic(&edges(&[(0, 1), (1, 2), (2, 3)])));
}
#[test]
fn acyclic_diamond() {
assert!(is_acyclic(&edges(&[(0, 1), (0, 2), (1, 3), (2, 3)])));
}
#[test]
fn cyclic_self_loop() {
assert!(!is_acyclic(&edges(&[(0, 0)])));
}
#[test]
fn cyclic_two_node() {
assert!(!is_acyclic(&edges(&[(0, 1), (1, 0)])));
}
#[test]
fn cyclic_triangle() {
assert!(!is_acyclic(&edges(&[(0, 1), (1, 2), (2, 0)])));
}
#[test]
fn cyclic_buried_in_dag() {
assert!(!is_acyclic(&edges(&[(0, 1), (1, 2), (2, 3), (3, 2)])));
}
#[test]
fn find_cycle_returns_none_for_dag() {
assert!(find_cycle(&edges(&[(0, 1), (1, 2), (2, 3)])).is_none());
}
#[test]
fn find_cycle_self_loop() {
let c = find_cycle(&edges(&[(0, 0)])).unwrap();
assert_eq!(c, vec![0]);
}
#[test]
fn find_cycle_triangle() {
let c = find_cycle(&edges(&[(0, 1), (1, 2), (2, 0)])).unwrap();
assert_eq!(c.len(), 3);
}
#[test]
fn find_cycle_buried() {
let c = find_cycle(&edges(&[(0, 1), (1, 2), (2, 3), (3, 2)])).unwrap();
assert_eq!(c.len(), 2);
assert!(c.contains(&2));
assert!(c.contains(&3));
}
}