Use depth-first search (DFS) to mark all individual connected components as visited:
dfs(node u) for each node v connected to u : if v is not visited : visited[v] = true dfs(v) for each node u: if u is not visited : visited[u] = true connected_component += 1 dfs(u)
The best way is to use this straightforward method which is linear time O(n).
Since you asked about the union-find algorithm:
for each node parent[node] = node for each node u : for each node v connected to u : if findset(u)!=findset(v) : union(u,v) **I assume you know about how findset and union works ** for each node if (parent[node] == node) connected_component += 1