-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0785-is-graph-bipartite.py
42 lines (32 loc) · 1.29 KB
/
0785-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
35
36
37
38
39
40
41
42
class Solution:
def isBipartiteBFS(self, graph: List[List[int]]) -> bool:
colors = [-1] * len(graph)
for i in range(len(graph)):
if colors[i] == -1:
q = deque([i])
colors[i] = 0
while q:
node = q.popleft()
for nbh in graph[node]:
if colors[nbh] == -1:
colors[nbh] = 1 - colors[node]
q.append(nbh)
elif colors[nbh] == colors[node]:
return False
return True
def isBipartiteDFS(self, graph: List[List[int]]) -> bool:
colors = [-1] * len(graph)
def dfs(node, c):
colors[node] = c
for nbh in graph[node]:
if colors[nbh] == -1:
if not dfs(nbh, 1 - c):
return False
elif colors[nbh] == colors[node]:
return False
return True
for i in range(len(graph)):
if colors[i] == -1:
if not dfs(i, 0):
return False
return True