How to recognise
items that only ever get connected, never split, and questions like "how many groups?", "are a and b connected?" or "which edge closes a cycle?".
How to solve problems like this
- Make every item its own group: parent[x] = x.
- Write find(x): follow parent until you reach an item that is its own parent. That item is the root.
- To connect a and b, find both roots. If they differ, set one root as the parent of the other and count one group less.
- Keep the trees flat: inside find, point each node you pass straight at the root, and hang the smaller tree under the bigger one.
Where it's used
- Finding objects in a picture. OpenCV (connectedComponents) and SciPy (ndimage.label) find connected spots of pixels: neighbouring pixels are joined into one group, and then each group gets a number.
- Splitting a photo into regions. Felzenszwalb's algorithm, which scikit-image has, merges neighbouring pixels into regions when they look alike, and keeps the regions in a union-find.