-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFriend Circles.py
51 lines (41 loc) · 1.01 KB
/
Friend Circles.py
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
def findCircleNum(M) -> int:
'''Using SCC => slow
def dfs(i):
visited[i] = True
for j in range(len(M[i])):
if M[i][j] and not visited[j]:
dfs(j)
topo.append(i)
topo = []
visited = [False] * len(M)
for i in range(len(M)):
if not visited[i]:
dfs(i)
for i in range(len(M)):
for j in range(0, i):
M[i][j], M[j][i] = M[j][i], M[i][j]
ans = 0
visited = [False] * len(M)
for i in topo:
if not visited[i]:
dfs(i)
ans += 1
return ans'''
# Using plain DFS => Fast
seen = set()
def dfs(node):
for adj, direct in enumerate(M[node]):
if direct and adj not in seen:
seen.add(adj)
dfs(adj)
ans = 0
for i in range(len(M)):
if i not in seen:
ans += 1
seen.add(i)
dfs(i)
return ans
M = [[1, 1, 0],
[1, 1, 1],
[0, 1, 1]]
print(findCircleNum(M))