-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount_the_number_of_connected_components.py
More file actions
46 lines (32 loc) · 1.15 KB
/
Count_the_number_of_connected_components.py
File metadata and controls
46 lines (32 loc) · 1.15 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
class Solution:
def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def DFS(currNode, vis):
totalNodes = []
stack = [currNode]
vis[currNode] = True
while stack:
node = stack.pop()
totalNodes.append(node)
for nei in graph[node]:
if not vis[nei]:
vis[nei] = True
stack.append(nei)
size = len(totalNodes)
for node in totalNodes:
if len(graph[node]) != size - 1:
return False
return True
vis = [False] * n
count = 0
for node in range(n):
if not vis[node]:
if len(graph[node]) == 0:
count += 1
else:
if DFS(node, vis) == True:
count += 1
return count