petgraph/algo/matching.rs
1use alloc::{collections::VecDeque, vec, vec::Vec};
2use core::hash::Hash;
3
4use crate::visit::{
5 EdgeRef, GraphBase, IntoEdges, IntoNeighbors, IntoNodeIdentifiers, NodeCount, NodeIndexable,
6 VisitMap, Visitable,
7};
8
9/// Computed
10/// [*matching*](https://en.wikipedia.org/wiki/Matching_(graph_theory)#Definitions)
11/// of the graph.
12pub struct Matching<G: GraphBase> {
13 graph: G,
14 mate: Vec<Option<G::NodeId>>,
15 n_edges: usize,
16}
17
18impl<G> Matching<G>
19where
20 G: GraphBase,
21{
22 fn new(graph: G, mate: Vec<Option<G::NodeId>>, n_edges: usize) -> Self {
23 Self {
24 graph,
25 mate,
26 n_edges,
27 }
28 }
29}
30
31impl<G> Matching<G>
32where
33 G: NodeIndexable,
34{
35 /// Gets the matched counterpart of given node, if there is any.
36 ///
37 /// Returns `None` if the node is not matched or does not exist.
38 pub fn mate(&self, node: G::NodeId) -> Option<G::NodeId> {
39 self.mate.get(self.graph.to_index(node)).and_then(|&id| id)
40 }
41
42 /// Iterates over all edges from the matching.
43 ///
44 /// An edge is represented by its endpoints. The graph is considered
45 /// undirected and every pair of matched nodes is reported only once.
46 pub fn edges(&self) -> MatchedEdges<'_, G> {
47 MatchedEdges {
48 graph: &self.graph,
49 mate: self.mate.as_slice(),
50 current: 0,
51 }
52 }
53
54 /// Iterates over all nodes from the matching.
55 pub fn nodes(&self) -> MatchedNodes<'_, G> {
56 MatchedNodes {
57 graph: &self.graph,
58 mate: self.mate.as_slice(),
59 current: 0,
60 }
61 }
62
63 /// Returns `true` if given edge is in the matching, or `false` otherwise.
64 ///
65 /// If any of the nodes does not exist, `false` is returned.
66 pub fn contains_edge(&self, a: G::NodeId, b: G::NodeId) -> bool {
67 match self.mate(a) {
68 Some(mate) => mate == b,
69 None => false,
70 }
71 }
72
73 /// Returns `true` if given node is in the matching, or `false` otherwise.
74 ///
75 /// If the node does not exist, `false` is returned.
76 pub fn contains_node(&self, node: G::NodeId) -> bool {
77 self.mate(node).is_some()
78 }
79
80 /// Gets the number of matched **edges**.
81 pub fn len(&self) -> usize {
82 self.n_edges
83 }
84
85 /// Returns `true` if the number of matched **edges** is 0.
86 pub fn is_empty(&self) -> bool {
87 self.len() == 0
88 }
89}
90
91impl<G> Matching<G>
92where
93 G: NodeCount,
94{
95 /// Returns `true` if the matching is perfect.
96 ///
97 /// A matching is
98 /// [*perfect*](https://en.wikipedia.org/wiki/Matching_(graph_theory)#Definitions)
99 /// if every node in the graph is incident to an edge from the matching.
100 pub fn is_perfect(&self) -> bool {
101 let n_nodes = self.graph.node_count();
102 n_nodes % 2 == 0 && self.n_edges == n_nodes / 2
103 }
104}
105
106trait WithDummy: NodeIndexable {
107 fn dummy_idx(&self) -> usize;
108 /// Convert `i` to a node index, returns None for the dummy node
109 fn try_from_index(&self, i: usize) -> Option<Self::NodeId>;
110}
111
112impl<G: NodeIndexable> WithDummy for G {
113 fn dummy_idx(&self) -> usize {
114 // Gabow numbers the vertices from 1 to n, and uses 0 as the dummy
115 // vertex. Our vertex indices are zero-based and so we use the node
116 // bound as the dummy node.
117 self.node_bound()
118 }
119
120 fn try_from_index(&self, i: usize) -> Option<Self::NodeId> {
121 if i != self.dummy_idx() {
122 Some(self.from_index(i))
123 } else {
124 None
125 }
126 }
127}
128
129pub struct MatchedNodes<'a, G: GraphBase> {
130 graph: &'a G,
131 mate: &'a [Option<G::NodeId>],
132 current: usize,
133}
134
135impl<G> Iterator for MatchedNodes<'_, G>
136where
137 G: NodeIndexable,
138{
139 type Item = G::NodeId;
140
141 fn next(&mut self) -> Option<Self::Item> {
142 while self.current != self.mate.len() {
143 let current = self.current;
144 self.current += 1;
145
146 if self.mate[current].is_some() {
147 return Some(self.graph.from_index(current));
148 }
149 }
150
151 None
152 }
153}
154
155pub struct MatchedEdges<'a, G: GraphBase> {
156 graph: &'a G,
157 mate: &'a [Option<G::NodeId>],
158 current: usize,
159}
160
161impl<G> Iterator for MatchedEdges<'_, G>
162where
163 G: NodeIndexable,
164{
165 type Item = (G::NodeId, G::NodeId);
166
167 fn next(&mut self) -> Option<Self::Item> {
168 while self.current != self.mate.len() {
169 let current = self.current;
170 self.current += 1;
171
172 if let Some(mate) = self.mate[current] {
173 // Check if the mate is a node after the current one. If not, then
174 // do not report that edge since it has been already reported (the
175 // graph is considered undirected).
176 if self.graph.to_index(mate) > current {
177 let this = self.graph.from_index(current);
178 return Some((this, mate));
179 }
180 }
181 }
182
183 None
184 }
185}
186
187/// \[Generic\] Compute a
188/// [*matching*](https://en.wikipedia.org/wiki/Matching_(graph_theory)) using a
189/// greedy heuristic.
190///
191/// The input graph is treated as if undirected. The underlying heuristic is
192/// unspecified, but is guaranteed to be bounded by *O(|V| + |E|)*. No
193/// guarantees about the output are given other than that it is a valid
194/// matching.
195///
196/// If you require a maximum matching, use [`maximum_matching`][1] function
197/// instead.
198///
199/// [1]: fn.maximum_matching.html
200pub fn greedy_matching<G>(graph: G) -> Matching<G>
201where
202 G: Visitable + IntoNodeIdentifiers + NodeIndexable + IntoNeighbors,
203 G::NodeId: Eq + Hash,
204 G::EdgeId: Eq + Hash,
205{
206 let (mates, n_edges) = greedy_matching_inner(&graph);
207 Matching::new(graph, mates, n_edges)
208}
209
210#[inline]
211fn greedy_matching_inner<G>(graph: &G) -> (Vec<Option<G::NodeId>>, usize)
212where
213 G: Visitable + IntoNodeIdentifiers + NodeIndexable + IntoNeighbors,
214{
215 let mut mate = vec![None; graph.node_bound()];
216 let mut n_edges = 0;
217 let visited = &mut graph.visit_map();
218
219 for start in graph.node_identifiers() {
220 let mut last = Some(start);
221
222 // Function non_backtracking_dfs does not expand the node if it has been
223 // already visited.
224 non_backtracking_dfs(graph, start, visited, |next| {
225 // Alternate matched and unmatched edges.
226 if let Some(pred) = last.take() {
227 mate[graph.to_index(pred)] = Some(next);
228 mate[graph.to_index(next)] = Some(pred);
229 n_edges += 1;
230 } else {
231 last = Some(next);
232 }
233 });
234 }
235
236 (mate, n_edges)
237}
238
239fn non_backtracking_dfs<G, F>(graph: &G, source: G::NodeId, visited: &mut G::Map, mut visitor: F)
240where
241 G: Visitable + IntoNeighbors,
242 F: FnMut(G::NodeId),
243{
244 if visited.visit(source) {
245 for target in graph.neighbors(source) {
246 if !visited.is_visited(&target) {
247 visitor(target);
248 non_backtracking_dfs(graph, target, visited, visitor);
249
250 // Non-backtracking traversal, stop iterating over the
251 // neighbors.
252 break;
253 }
254 }
255 }
256}
257
258#[derive(Clone, Copy, Default)]
259enum Label<G: GraphBase> {
260 #[default]
261 None,
262 Start,
263 // If node v is outer node, then label(v) = w is another outer node on path
264 // from v to start u.
265 Vertex(G::NodeId),
266 // If node v is outer node, then label(v) = (r, s) are two outer vertices
267 // (connected by an edge)
268 Edge(G::EdgeId, [G::NodeId; 2]),
269 // Flag is a special label used in searching for the join vertex of two
270 // paths.
271 Flag(G::EdgeId),
272}
273
274impl<G: GraphBase> Label<G> {
275 fn is_outer(&self) -> bool {
276 self != &Label::None && !matches!(self, Label::Flag(_))
277 }
278
279 fn is_inner(&self) -> bool {
280 !self.is_outer()
281 }
282
283 fn to_vertex(&self) -> Option<G::NodeId> {
284 match *self {
285 Label::Vertex(v) => Some(v),
286 _ => None,
287 }
288 }
289
290 fn is_flagged(&self, edge: G::EdgeId) -> bool {
291 matches!(self, Label::Flag(flag) if flag == &edge)
292 }
293}
294
295impl<G: GraphBase> PartialEq for Label<G> {
296 fn eq(&self, other: &Self) -> bool {
297 match (self, other) {
298 (Label::None, Label::None) => true,
299 (Label::Start, Label::Start) => true,
300 (Label::Vertex(v1), Label::Vertex(v2)) => v1 == v2,
301 (Label::Edge(e1, _), Label::Edge(e2, _)) => e1 == e2,
302 (Label::Flag(e1), Label::Flag(e2)) => e1 == e2,
303 _ => false,
304 }
305 }
306}
307
308/// \[Generic\] Compute the [*maximum
309/// matching*](https://en.wikipedia.org/wiki/Matching_(graph_theory)) using
310/// [Gabow's algorithm][1].
311///
312/// [1]: https://dl.acm.org/doi/10.1145/321941.321942
313///
314/// The input graph is treated as if undirected. The algorithm runs in
315/// *O(|V|³)*. An algorithm with a better time complexity might be used in the
316/// future.
317///
318/// **Panics** if `g.node_bound()` is `usize::MAX`.
319///
320/// # Examples
321///
322/// ```
323/// use petgraph::prelude::*;
324/// use petgraph::algo::maximum_matching;
325///
326/// // The example graph:
327/// //
328/// // +-- b ---- d ---- f
329/// // / | |
330/// // a | |
331/// // \ | |
332/// // +-- c ---- e
333/// //
334/// // Maximum matching: { (a, b), (c, e), (d, f) }
335///
336/// let mut graph: UnGraph<(), ()> = UnGraph::new_undirected();
337/// let a = graph.add_node(());
338/// let b = graph.add_node(());
339/// let c = graph.add_node(());
340/// let d = graph.add_node(());
341/// let e = graph.add_node(());
342/// let f = graph.add_node(());
343/// graph.extend_with_edges(&[(a, b), (a, c), (b, c), (b, d), (c, e), (d, e), (d, f)]);
344///
345/// let matching = maximum_matching(&graph);
346/// assert!(matching.contains_edge(a, b));
347/// assert!(matching.contains_edge(c, e));
348/// assert_eq!(matching.mate(d), Some(f));
349/// assert_eq!(matching.mate(f), Some(d));
350/// ```
351pub fn maximum_matching<G>(graph: G) -> Matching<G>
352where
353 G: Visitable + NodeIndexable + IntoNodeIdentifiers + IntoEdges,
354{
355 // The dummy identifier needs an unused index
356 assert_ne!(
357 graph.node_bound(),
358 usize::MAX,
359 "The input graph capacity should be strictly less than core::usize::MAX."
360 );
361
362 // Greedy algorithm should create a fairly good initial matching. The hope
363 // is that it speeds up the computation by doing les work in the complex
364 // algorithm.
365 let (mut mate, mut n_edges) = greedy_matching_inner(&graph);
366
367 // Gabow's algorithm uses a dummy node in the mate array.
368 mate.push(None);
369 let len = graph.node_bound() + 1;
370 debug_assert_eq!(mate.len(), len);
371
372 let mut label: Vec<Label<G>> = vec![Label::None; len];
373 let mut first_inner = vec![usize::MAX; len];
374 let visited = &mut graph.visit_map();
375
376 for start in 0..graph.node_bound() {
377 if mate[start].is_some() {
378 // The vertex is already matched. A start must be a free vertex.
379 continue;
380 }
381
382 // Begin search from the node.
383 label[start] = Label::Start;
384 first_inner[start] = graph.dummy_idx();
385 graph.reset_map(visited);
386
387 // start is never a dummy index
388 let start = graph.from_index(start);
389
390 // Queue will contain outer vertices that should be processed next. The
391 // start vertex is considered an outer vertex.
392 let mut queue = VecDeque::new();
393 queue.push_back(start);
394 // Mark the start vertex so it is not processed repeatedly.
395 visited.visit(start);
396
397 'search: while let Some(outer_vertex) = queue.pop_front() {
398 for edge in graph.edges(outer_vertex) {
399 if edge.source() == edge.target() {
400 // Ignore self-loops.
401 continue;
402 }
403
404 let other_vertex = edge.target();
405 let other_idx = graph.to_index(other_vertex);
406
407 if mate[other_idx].is_none() && other_vertex != start {
408 // An augmenting path was found. Augment the matching. If
409 // `other` is actually the start node, then the augmentation
410 // must not be performed, because the start vertex would be
411 // incident to two edges, which violates the matching
412 // property.
413 mate[other_idx] = Some(outer_vertex);
414 augment_path(&graph, outer_vertex, other_vertex, &mut mate, &label);
415 n_edges += 1;
416
417 // The path is augmented, so the start is no longer free
418 // vertex. We need to begin with a new start.
419 break 'search;
420 } else if label[other_idx].is_outer() {
421 // The `other` is an outer vertex (a label has been set to
422 // it). An odd cycle (blossom) was found. Assign this edge
423 // as a label to all inner vertices in paths P(outer) and
424 // P(other).
425 find_join(
426 &graph,
427 edge,
428 &mate,
429 &mut label,
430 &mut first_inner,
431 |labeled| {
432 if visited.visit(labeled) {
433 queue.push_back(labeled);
434 }
435 },
436 );
437 } else {
438 let mate_vertex = mate[other_idx];
439 let mate_idx = mate_vertex.map_or(graph.dummy_idx(), |id| graph.to_index(id));
440
441 if label[mate_idx].is_inner() {
442 // Mate of `other` vertex is inner (no label has been
443 // set to it so far). But it actually is an outer vertex
444 // (it is on a path to the start vertex that begins with
445 // a matched edge, since it is a mate of `other`).
446 // Assign the label of this mate to the `outer` vertex,
447 // so the path for it can be reconstructed using `mate`
448 // and this label.
449 label[mate_idx] = Label::Vertex(outer_vertex);
450 first_inner[mate_idx] = other_idx;
451 }
452
453 // Add the vertex to the queue only if it's not the dummy and this is its first
454 // discovery.
455 if let Some(mate_vertex) = mate_vertex {
456 if visited.visit(mate_vertex) {
457 queue.push_back(mate_vertex);
458 }
459 }
460 }
461 }
462 }
463
464 // Reset the labels. All vertices are inner for the next search.
465 for lbl in label.iter_mut() {
466 *lbl = Label::None;
467 }
468 }
469
470 // Discard the dummy node.
471 mate.pop();
472
473 Matching::new(graph, mate, n_edges)
474}
475
476fn find_join<G, F>(
477 graph: &G,
478 edge: G::EdgeRef,
479 mate: &[Option<G::NodeId>],
480 label: &mut [Label<G>],
481 first_inner: &mut [usize],
482 mut visitor: F,
483) where
484 G: IntoEdges + NodeIndexable + Visitable,
485 F: FnMut(G::NodeId),
486{
487 // Simultaneously traverse the inner vertices on paths P(source) and
488 // P(target) to find a join vertex - an inner vertex that is shared by these
489 // paths.
490 let source = graph.to_index(edge.source());
491 let target = graph.to_index(edge.target());
492
493 let mut left = first_inner[source];
494 let mut right = first_inner[target];
495
496 if left == right {
497 // No vertices can be labeled, since both paths already refer to a
498 // common vertex - the join.
499 return;
500 }
501
502 // Flag the (first) inner vertices. This ensures that they are assigned the
503 // join as their first inner vertex.
504 let flag = Label::Flag(edge.id());
505 label[left] = flag;
506 label[right] = flag;
507
508 // Find the join.
509 let join = loop {
510 // Swap the sides. Do not swap if the right side is already finished.
511 if right != graph.dummy_idx() {
512 core::mem::swap(&mut left, &mut right);
513 }
514
515 // Set left to the next inner vertex in P(source) or P(target).
516 // The unwraps are safe because left is not the dummy node.
517 let left_mate = graph.to_index(mate[left].unwrap());
518 let next_inner = label[left_mate].to_vertex().unwrap();
519 left = first_inner[graph.to_index(next_inner)];
520
521 if !label[left].is_flagged(edge.id()) {
522 // The inner vertex is not flagged yet, so flag it.
523 label[left] = flag;
524 } else {
525 // The inner vertex is already flagged. It means that the other side
526 // had to visit it already. Therefore it is the join vertex.
527 break left;
528 }
529 };
530
531 // Label all inner vertices on P(source) and P(target) with the found join.
532 for endpoint in [source, target].iter().copied() {
533 let mut inner = first_inner[endpoint];
534 while inner != join {
535 // Notify the caller about labeling a vertex.
536 if let Some(ix) = graph.try_from_index(inner) {
537 visitor(ix);
538 }
539
540 label[inner] = Label::Edge(edge.id(), [edge.source(), edge.target()]);
541 first_inner[inner] = join;
542 let inner_mate = graph.to_index(mate[inner].unwrap());
543 let next_inner = label[inner_mate].to_vertex().unwrap();
544 inner = first_inner[graph.to_index(next_inner)];
545 }
546 }
547
548 for (vertex_idx, vertex_label) in label.iter().enumerate() {
549 // To all outer vertices that are on paths P(source) and P(target) until
550 // the join, se the join as their first inner vertex.
551 if vertex_idx != graph.dummy_idx()
552 && vertex_label.is_outer()
553 && label[first_inner[vertex_idx]].is_outer()
554 {
555 first_inner[vertex_idx] = join;
556 }
557 }
558}
559
560fn augment_path<G>(
561 graph: &G,
562 outer: G::NodeId,
563 other: G::NodeId,
564 mate: &mut [Option<G::NodeId>],
565 label: &[Label<G>],
566) where
567 G: NodeIndexable,
568{
569 let outer_idx = graph.to_index(outer);
570
571 let temp = mate[outer_idx];
572 let temp_idx = temp.map_or(graph.dummy_idx(), |id| graph.to_index(id));
573 mate[outer_idx] = Some(other);
574
575 if mate[temp_idx] != Some(outer) {
576 // We are at the end of the path and so the entire path is completely
577 // rematched/augmented.
578 } else if let Label::Vertex(vertex) = label[outer_idx] {
579 // The outer vertex has a vertex label which refers to another outer
580 // vertex on the path. So we set this another outer node as the mate for
581 // the previous mate of the outer node.
582 mate[temp_idx] = Some(vertex);
583 if let Some(temp) = temp {
584 augment_path(graph, vertex, temp, mate, label);
585 }
586 } else if let Label::Edge(_, [source, target]) = label[outer_idx] {
587 // The outer vertex has an edge label which refers to an edge in a
588 // blossom. We need to augment both directions along the blossom.
589 augment_path(graph, source, target, mate, label);
590 augment_path(graph, target, source, mate, label);
591 } else {
592 panic!("Unexpected label when augmenting path");
593 }
594}