blob: 6343e9fdf64d60728631337751c8cdc0442761dc [file] [log] [blame]
Parker Schuh6691f192017-01-14 17:01:02 -08001#ifndef _AOS_VISION_BLOB_DISJOINT_SET_H_
2#define _AOS_VISION_BLOB_DISJOINT_SET_H_
3
4#include <vector>
5
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -08006namespace aos::vision {
Parker Schuh6691f192017-01-14 17:01:02 -08007
Brian Silvermanb27e6b72019-03-10 16:17:42 -07008// Disjoint set algorithm, which is similar to what this class does:
Parker Schuh6691f192017-01-14 17:01:02 -08009// https://en.wikipedia.org/wiki/Disjoint-set_data_structure
10class DisjointSet {
11 public:
12 DisjointSet() {}
13 DisjointSet(int node_count) : nodes_(node_count, -1) {}
14 // Adds another node. Not connected to anything.
15 // Returns id of the additional node for tracking purposes.
16 int Add() {
17 nodes_.push_back(-1);
18 return nodes_.size() - 1;
19 }
20 int &operator[](int id) { return nodes_[id]; }
21 // Find returns the canonical id of the set containing id.
22 // This id is an arbitrary artifact of the merge process.
23 int Find(int id) {
24 int chained_id = nodes_[id];
25 if (chained_id <= -1) {
26 return id;
27 }
28 return nodes_[id] = Find(chained_id);
29 }
30 // The blob mergeing needs to explicitly override the default union behavior.
31 void ExplicitUnion(int parent_id, int child_id) {
32 nodes_[parent_id] = child_id;
33 }
34 // Check to see if this node is the canonical id.
35 bool IsRoot(int id) { return nodes_[id] < 0; }
36
37 private:
38 // Implemented over a vector.
39 std::vector<int> nodes_;
40};
41
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080042} // namespace aos::vision
Parker Schuh6691f192017-01-14 17:01:02 -080043
44#endif // _AOS_VISION_BLOB_DISJOINT_SET_H_