Adds UnionFind to check for cycles