[LeetCode] Count the Number of Complete Components

2685. Count the Number of Complete Components

You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi.

Return the number of complete connected components of the graph.

A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.

A connected component is said to be complete if there exists an edge between every pair of its vertices.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

class Solution {
int uf[101];
int find(int u) {
return uf[u] == u ? u : uf[u] = find(uf[u]);
}
void uni(int u, int v) {
int pu = find(u), pv = find(v);
uf[pu ] = uf[pv] = min(pu,pv);
}
public:
int countCompleteComponents(int n, vector<vector<int>>& edges) {
for(int i = 0; i < n; i++) uf[i] = i;
unordered_set<int> adj[n];
for(auto e : edges) {
int u = e[0], v = e[1];
uni(u,v);
adj[u].insert(v);
adj[v].insert(u);
}
unordered_map<int, vector<int>> g;
for(int i = 0; i < n; i++) {
g[find(i)].push_back(i);
}
int res = 0;
for(auto [k, vec] : g) {
bool ok = true;
for(int i = 0; i < vec.size() and ok; i++) {
for(int j = i + 1; j < vec.size() and ok; j++) {
if(!adj[vec[i]].count(vec[j])) ok = false;
}
}
res += ok;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/14/PS/LeetCode/count-the-number-of-complete-components/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.