-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbipartite_graph.py
More file actions
44 lines (33 loc) · 1.04 KB
/
bipartite_graph.py
File metadata and controls
44 lines (33 loc) · 1.04 KB
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
"""Given an undirected graph G, check whether it is bipartite.
Recall that a graph is bipartite if its vertices can be divided
into two independent sets, U and V,
such that no edge connects vertices of the same set."""
from collections import defaultdict, deque
def bipartite_check(g, s):
"""Check whether a graph is bipartite or not."""
color = defaultdict(str)
queue = deque()
queue.append(s)
color[s] = "Red"
while queue:
d = queue.pop()
for i in g:
for v in g[i]:
if v == i:
return False
for v in g[d]:
if not color[v]:
if color[d] == "Red":
color[v] = "Blue"
else:
color[v] = "Red"
queue.append(v)
elif color[v] == color[d]:
return False
return True
g = {"a": ["b", "c"],
"b": ["a", "d"],
"c": ["a", "d"],
"d": ["b", "c", "d"]
}
print(bipartite_check(g, 'a'))