8000 Completed bipartite check. · anubhavcoder/practice-python@247c359 · GitHub
[go: up one dir, main page]

Skip to content

Commit 247c359

Browse files
committed
Completed bipartite check.
1 parent 4f10624 commit 247c359

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

graphs/undirected_graph_matrix.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,30 @@ def bfs(self):
9999

100100
return parents
101101

102+
def is_bipartite(self):
103+
"""
104+
Returns true if graph is bipartite
105+
:return:
106+
"""
107+
is_bipartite = True
108+
colorings = {}
109+
to_visit = queue.Queue()
110+
to_visit.put(0)
111+
colorings[0] = 0
112+
113+
while not to_visit.empty() and is_bipartite:
114+
v = to_visit.get()
115+
116+
for u in self.get_neighbor(v):
117+
if u not in colorings:
118+
colorings[u] = 1 - colorings[v]
119+
to_visit.put(u)
120+
elif colorings[u] == colorings[v]:
121+
is_bipartite = False
122+
break
123+
124+
return is_bipartite
125+
102126

103127
def get_test_graph_1():
104128
udg = UndirectedGraph(9)
@@ -118,6 +142,21 @@ def get_test_graph_1():
118142
return udg
119143

120144

145+
def get_test_graph_2():
146+
udg = UndirectedGraph(8)
147+
udg.add_edge(0, 1)
148+
udg.add_edge(0, 5)
149+
udg.add_edge(2, 1)
150+
udg.add_edge(2, 3)
151+
udg.add_edge(2, 5)
152+
udg.add_edge(4, 3)
153+
udg.add_edge(4, 5)
154+
udg.add_edge(4, 7)
155+
udg.add_edge(6, 7)
156+
157+
return udg
158+
159+
121160
def test_dfs_recursive():
122161
udg = get_test_graph_1()
123162
p1 = udg.dfs_recursive()
@@ -136,10 +175,19 @@ def test_bfs():
136175
assert(p1 == {0: 1, 1: 0, 2: 1, 3: 2, 4: 3, 5: 3, 6: 7, 7: 1, 8: 7})
137176

138177

178+
def test_bipartite():
179+
udg = get_test_graph_1()
180+
assert(udg.is_bipartite() == False)
181+
182+
udg2 = get_test_graph_2()
183+
assert (udg2.is_bipartite() == True)
184+
185+
139186
def main():
140187
test_dfs_recursive()
141188
test_dfs_iterative()
142189
test_bfs()
190+
test_bipartite()
143191

144192
print("Tests complete.")
145193

0 commit comments

Comments
 (0)
0