Graph::UnionFind(3pm)

πŸ’– Graph::UnionFind πŸ’–

okay bestie, so this is the Graph::UnionFind page from the User Contributed Perl Documentation section of the manual (that's the 3pm zone, iykyk) β€” it's a whole little module and honestly it's giving main character energy for a data structure.


🌸 NAME 🌸

Graph::UnionFind β€” union-find data structures 🫢


✨ SYNOPSIS ✨

like, here's the whole vibe in code, no cap:

use Graph::UnionFind;
my $uf = Graph::UnionFind->new;

# Add the vertices to the data structure.
$uf->add($u);
$uf->add($v);

# Join the partitions of the vertices.
$uf->union( $u, $v );

# Find the partitions the vertices belong to
# in the union-find data structure.  If they
# are equal, they are in the same partition.
# If the vertex has not been seen,
# undef is returned.
my $pu = $uf->find( $u );
my $pv = $uf->find( $v );
$uf->same($u, $v) # Equal to $pu eq $pv.

# Has the union-find seen this vertex?
$uf->has( $v )

πŸ¦‹ DESCRIPTION πŸ¦‹

so union-find is this special data structure that tracks how a set gets partitioned into subsets β€” a problem that also goes by the name disjoint sets, in case you see that name out in the wild and go "wait, do I know her?" πŸŽ€

Graph::UnionFind is what powers connected_components in Graph, connected_component in Graph, and same_connected_components in Graph β€” but only if you pass a true unionfind parameter when you create an undirected graph. that's the deal, fr fr. πŸ’…

and bestie, important: union-find is one way. you cannot (easily) 'ununion' vertices once you have 'unioned' them. it's giving "no takebacks". 😭 that is exactly why Graph throws an exception if you try to delete edges from a union-find graph β€” it is not playing about it.


πŸ‘‘ API πŸ‘‘

πŸ’– add

$uf->add(@v)

adds the vertices to the union-find. simple as that, slay. ✨

πŸ’– union

$uf->union([$u, $v], [$w, $x], ...)

adds the edge u-v to the union-find. it also implicitly adds the vertices, so you don't gotta do that part yourself. 🫢

πŸ’– find

@partitions = $uf->find(@v)

for each vertex you hand it, it returns the union-find partition that vertex belongs to β€” or undef if it hasn't been added. undef is the "never seen her" of return values. πŸ™ˆ

πŸ’– new

$uf = Graph::UnionFind->new()

the constructor. the origin story. the birth of the vibe. 🌱

πŸ’– same

$uf->same($u, $v)

returns true if the vertices belong to the same union-find partition the vertex v belongs to, and false otherwise. πŸŽ€


Jarkko Hietaniemi jhi@iki.fi β€” icon, legend, the moment. πŸ‘‘


πŸ’œ LICENSE πŸ’œ

this module is licensed under the same terms as Perl itself. periodt. πŸŽ€


and that's the whole page, bestie!! thank you for coming to my TED talk πŸ’…

perl v5.40.1 Β· 2025-03-28 Β· Graph::UnionFind(3pm) β€” mwah, go union some vertices, you got this πŸ¦‹βœ¨

πŸ“¦ where this page comes from