-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfriend_circles.py
73 lines (55 loc) · 1.46 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#
# https://leetcode.com/problems/friend-circles/
#
# NOTE: another input format: Y, N instead of 1, 0
#
def dfs(temp, v, visited, friends):
if visited[v]:
return
visited[v] = True
temp.append(v)
for idx, val in enumerate(friends[v]):
if val == 'Y':
dfs(temp, idx, visited, friends)
def friend_circles(friends):
num_vertexes = len(friends)
visited = []
cc = []
for i in range(num_vertexes):
visited.append(False)
for v in range(num_vertexes):
if not visited[v]:
temp = []
dfs(temp, v, visited, friends)
if temp:
cc.append(temp)
return len(cc)
def run_tests():
input = [
['Y', 'Y', 'N', 'N'],
['Y', 'Y', 'Y', 'N'],
['N', 'Y', 'Y', 'N'],
['N', 'N', 'N', 'Y']
] # answer is two
input1 = [
['Y', 'N', 'N', 'N', 'N'],
['N', 'Y', 'N', 'N', 'N'],
['N', 'N', 'Y', 'N', 'N'],
['N', 'N', 'N', 'Y', 'N'],
['N', 'N', 'N', 'N', 'Y']
] # answer is five
input2 = [
['Y', 'Y', 'N'],
['Y', 'Y', 'N'],
['N', 'N', 'Y']
] # answer is two
input3 = [
['Y', 'Y', 'N'],
['Y', 'Y', 'Y'],
['N', 'Y', 'Y']
] # answer is one
assert friend_circles(input) == 2
assert friend_circles(input1) == 5
assert friend_circles(input2) == 2
assert friend_circles(input3) == 1
run_tests()