-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathis_graph_bipartite.py
34 lines (29 loc) · 1021 Bytes
/
is_graph_bipartite.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
class Solution(object):
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
grps = {}
visited = [0 for i in range(len(graph))]
s = -1
if len(graph) <= 2:
return True
for i in range(len(graph)):
if i not in grps:
grps[i] = -1
stack = [i]
while stack:
node = stack.pop()
if visited[node]:
continue
visited[node] = 1
while graph[node]:
neighbor = graph[node].pop(0)
if neighbor in grps and grps[neighbor] == grps[node]:
return False
if neighbor not in grps:
grps[neighbor] = grps[node] * (-1)
if not visited[neighbor]:
stack.append(neighbor)
return True