forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
divide-nodes-into-the-maximum-number-of-groups.py
123 lines (116 loc) · 3.25 KB
/
divide-nodes-into-the-maximum-number-of-groups.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# Time: O(n^2)
# Space: O(n)
# iterative dfs, bfs
class Solution(object):
def magnificentSets(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def iter_dfs(u):
group = []
stk = [u]
lookup[u] = 0
while stk:
u = stk.pop()
group.append(u)
for v in adj[u]:
if lookup[v] != -1:
if lookup[v] == lookup[u]: # odd-length cycle, not bipartite
return []
continue
lookup[v] = lookup[u]^1
stk.append(v)
return group
def bfs(u):
result = 0
lookup = [False]*n
q = [u]
lookup[u] = True
while q:
new_q = []
for u in q:
for v in adj[u]:
if lookup[v]:
continue
lookup[v] = True
new_q.append(v)
q = new_q
result += 1
return result
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u-1].append(v-1)
adj[v-1].append(u-1)
result = 0
lookup = [-1]*n
for u in xrange(n):
if lookup[u] != -1:
continue
group = iter_dfs(u)
if not group:
return -1
result += max(bfs(u) for u in group)
return result
# Time: O(n^2)
# Space: O(n)
# bfs
class Solution2(object):
def magnificentSets(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def bfs(u):
group = []
q = {u}
lookup[u] = True
while q:
new_q = set()
for u in q:
group.append(u)
for v in adj[u]:
if lookup[v]:
continue
lookup[v] = True
new_q.add(v)
q = new_q
return group
def bfs2(u):
result = 0
lookup = [False]*n
q = {u}
lookup[u] = True
while q:
new_q = set()
for u in q:
for v in adj[u]:
if v in q:
return 0
if lookup[v]:
continue
lookup[v] = True
new_q.add(v)
q = new_q
result += 1
return result
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u-1].append(v-1)
adj[v-1].append(u-1)
result = 0
lookup = [0]*n
for u in xrange(n):
if lookup[u]:
continue
group = bfs(u)
mx = 0
for u in group:
d = bfs2(u)
if d == 0:
return -1
mx = max(mx, d)
result += mx
return result