Description from wiki: a disjoint-set data structure, also called a union–find data structure or merge–find set, is a data structure that stores a collection of disjoint (non-overlapping) sets
you can easily solve leetcode: 547. Number of Provinces w/ UF.
get UF template at github/sky-bro/AC/Algorithms/Union Find
Template
UF datastructure is very simple, it has only two key functions: U
and F
.
- use
U
(union) to connect two nodes, so they belong to the same set; - use
F
(find) to find the root of a node (or the group id of the node)
We use ids
to store the parent of every node, ids[i]
is the i-th node’s parent. if ids[i] == i
means i
is the root if its group, we can say the group id is i
.
So, different root/group id means nodes are in different groups, whereas same root/group id means two nodes are in the same group.
simle
|
|
full
part from U
and F
, based on your needs, you can add these functions:
int group_count()
, count the number of sets/groups – initializegroup_cnt
as n (each node as a group), every timeU
unions two different groups,--group_count
.int count(int x)
, count the size of the group of node x – whenU
unions two different groups, add one group’s size to another (the new root).bool connected(int p, int q)
, check if two nodes are in the same group.
|
|
Solution to lc problem 547
you can also solve this problem with dfs: github/sky-bro/AC/leetcode.com/0547 Friend Circles/main.cpp, lc has changed the name of this problem to “Number of Provinces”
|
|