knotrel_core/reference.rs
1//! Original ordered-adjacency BFS retained for differential checks and benchmarks.
2
3use crate::{GraphError, NodeId};
4use std::collections::{BTreeMap, BTreeSet, VecDeque, btree_map::Entry};
5
6/// An undirected simple graph with exact connectivity queries.
7///
8/// Every stored edge appears in both endpoints' adjacency sets. Sets exclude
9/// self-loops and duplicate edges; every endpoint has a vertex entry. Deleting
10/// an edge preserves its vertices. Storage is O(V + E), where V and E are the
11/// current vertex and undirected edge counts.
12///
13/// **Internal test oracle; no stability promise.** It exists for differential
14/// tests and benchmarks and may change or disappear in any release; see
15/// `docs/stability.md`. Use [`Graph`](crate::Graph) or
16/// [`ConnectivityGraph`](crate::ConnectivityGraph) instead.
17#[derive(Debug, Default)]
18pub struct ReferenceGraph {
19 adjacency: BTreeMap<NodeId, BTreeSet<NodeId>>,
20 edges: usize,
21}
22
23impl ReferenceGraph {
24 /// Creates an empty graph in O(1) time.
25 #[must_use]
26 pub fn new() -> Self {
27 Self::default()
28 }
29
30 /// Adds an isolated vertex, returning `true` only if it was absent.
31 ///
32 /// An existing vertex and its edges are unchanged. Worst-case time: O(log V).
33 pub fn add_node(&mut self, node: NodeId) -> bool {
34 if let Entry::Vacant(entry) = self.adjacency.entry(node) {
35 entry.insert(BTreeSet::new());
36 true
37 } else {
38 false
39 }
40 }
41
42 /// Inserts an undirected edge, creating absent endpoints.
43 ///
44 /// Returns `true` only when the edge is new. Reversed endpoints identify
45 /// the same edge. Worst-case time: O(log V).
46 ///
47 /// # Errors
48 /// Returns [`GraphError::SelfLoop`] for equal endpoints, without changing the graph.
49 pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
50 GraphError::check_distinct(source, target)?;
51 let inserted = self.adjacency.entry(source).or_default().insert(target);
52 self.adjacency.entry(target).or_default().insert(source);
53 self.edges += usize::from(inserted);
54 Ok(inserted)
55 }
56
57 /// Removes an undirected edge while preserving both vertices.
58 ///
59 /// Returns `false` if the edge or either endpoint is absent. Worst-case
60 /// time: O(log V).
61 ///
62 /// # Errors
63 /// Returns [`GraphError::SelfLoop`] for equal endpoints, without changing the graph.
64 pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
65 GraphError::check_distinct(source, target)?;
66 let removed = self
67 .adjacency
68 .get_mut(&source)
69 .is_some_and(|neighbors| neighbors.remove(&target));
70 if removed {
71 // Symmetric adjacency guarantees the other endpoint exists. Update
72 // both directions before returning to preserve the graph invariant.
73 self.adjacency
74 .get_mut(&target)
75 .expect("edge endpoint exists")
76 .remove(&source);
77 self.edges -= 1;
78 }
79 Ok(removed)
80 }
81
82 /// Reports whether a path exists between two existing vertices.
83 ///
84 /// An existing vertex connects to itself by the empty path. Worst-case time
85 /// is O((V + E) log V); scratch memory is O(V). These are worst-case bounds,
86 /// not amortized bounds. Traversal stops early when the target is found.
87 ///
88 /// # Errors
89 /// Returns [`GraphError::UnknownNode`] for an absent endpoint, checking
90 /// `source` before `target`.
91 pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
92 for node in [source, target] {
93 if !self.adjacency.contains_key(&node) {
94 return Err(GraphError::UnknownNode { node });
95 }
96 }
97 if source == target {
98 return Ok(true);
99 }
100
101 // Breadth-first search: every queued vertex is reachable from source.
102 // Marking at enqueue time means a vertex enters the queue at most once,
103 // including on cycles. Exhausting the queue explores the entire source
104 // component, so an undiscovered target cannot be connected. Ordered
105 // sets make membership O(log V) and traversal reproducible.
106 let mut visited = BTreeSet::from([source]);
107 let mut pending = VecDeque::from([source]);
108 while let Some(node) = pending.pop_front() {
109 for &neighbor in &self.adjacency[&node] {
110 if neighbor == target {
111 return Ok(true);
112 }
113 if visited.insert(neighbor) {
114 pending.push_back(neighbor);
115 }
116 }
117 }
118 Ok(false)
119 }
120
121 /// Returns the number of vertices, including isolated ones, in O(1) time.
122 #[must_use]
123 pub fn node_count(&self) -> usize {
124 self.adjacency.len()
125 }
126
127 /// Returns the number of undirected edges in O(1) time.
128 #[must_use]
129 pub fn edge_count(&self) -> usize {
130 self.edges
131 }
132}