Skip to content

Commit d081969

Browse files
authored
Create count-the-number-of-complete-components.py
1 parent 030580f commit d081969

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# bfs
5+
class Solution(object):
6+
def countCompleteComponents(self, n, edges):
7+
"""
8+
:type n: int
9+
:type edges: List[List[int]]
10+
:rtype: int
11+
"""
12+
def bfs(u):
13+
if lookup[u]:
14+
return False
15+
v_cnt = e_cnt = 0
16+
lookup[u] = True
17+
q = [u]
18+
while q:
19+
new_q = []
20+
v_cnt += len(q)
21+
for u in q:
22+
e_cnt += len(adj[u])
23+
for v in adj[u]:
24+
if lookup[v]:
25+
continue
26+
lookup[v] = True
27+
new_q.append(v)
28+
q = new_q
29+
return v_cnt*(v_cnt-1) == e_cnt
30+
31+
adj = [[] for _ in xrange(n)]
32+
for u, v in edges:
33+
adj[u].append(v)
34+
adj[v].append(u)
35+
lookup = [False]*n
36+
return sum(bfs(u) for u in xrange(n) if not lookup[u])

0 commit comments

Comments
 (0)