Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union-Find or DFS: which one is better to find connected component?

Tags:

Union-Find and DFS could be both used to find connectivity. Which one is better in which condition?

like image 380
Peterxwl Avatar asked Feb 08 '15 19:02

Peterxwl


People also ask

Can DFS be used to find a strongly connected components?

Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices.

Is DSU faster than DFS?

Note: From my Java submission results the optmized DSU solutions is the fastest solution at 10 ms, probably because it uses int[] instead of the Map objects in the DFS solutions below.

What is the purpose of union-find?

A union-find algorithm is an algorithm that performs two useful operations on such a data structure: Find: Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset. Union: Join two subsets into a single subset.

What is the time complexity of union-find?

Using link-by-size, any UNION or FIND operation takes O(log n) time in the worst case, where n is the number of elements.


1 Answers

The union-find algorithm is best suited for situations where the equivalence relationship is changing, i.e., there are "Union" operations which need to be performed on your set of partitions. Given a fixed undirected graph, you don't have the equivalence relationships changing at all - the edges are all fixed. OTOH, if you have a graph with new edges being added, DFS won't cut it. While DFS is asymptotically faster than union-find, in practice, the likely deciding factor would be the actual problem that you are trying to solve.

tl;dr - Static graph? DFS! Dynamic graph? Union-find!

like image 65
Pradhan Avatar answered Sep 19 '22 15:09

Pradhan