-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2685. Count_the_Number_of_Complete_Components.py
More file actions
67 lines (44 loc) · 2.08 KB
/
2685. Count_the_Number_of_Complete_Components.py
File metadata and controls
67 lines (44 loc) · 2.08 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]
Output: 3
Explanation: From the picture above, one can see that all of the components of this graph are complete.
Example 2:
Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]]
Output: 1
Explanation: The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1.
Constraints:
1 <= n <= 50
0 <= edges.length <= n * (n - 1) / 2
edges[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
There are no repeated edges.
############################# Solution ###################################
class Solution:
def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:
def dfs(v, res):
if v in visit:
return
visit.add(v)
res.append(v)
for nei in adj[v]:
dfs(nei,res)
return res
res =0
adj = defaultdict(list)
for v1,v2 in edges:
adj[v1].append(v2)
adj[v2].append(v1)
res =0
visit = set()
for v in range(n):
if v in visit:
continue
Component = dfs(v,[])
if all ([len(Component) -1 == len(adj[v2]) for v2 in Component]):
res +=1
return res