Skip to content

Commit a65efd4

Browse files
Erfaniaapoyea
authored andcommitted
Implement check_bipartite_graph using DFS. (TheAlgorithms#808)
1 parent 13c0c16 commit a65efd4

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

graphs/check_bipartite_graph_dfs.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Check whether Graph is Bipartite or Not using DFS
2+
3+
# A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
4+
# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex
5+
# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V,
6+
# or u belongs to V and v to U. We can also say that there is no edge that connects
7+
# vertices of same set.
8+
def check_bipartite_dfs(l):
9+
visited = [False] * len(l)
10+
color = [-1] * len(l)
11+
12+
def dfs(v, c):
13+
visited[v] = True
14+
color[v] = c
15+
for u in l[v]:
16+
if not visited[u]:
17+
dfs(u, 1 - c)
18+
19+
for i in range(len(l)):
20+
if not visited[i]:
21+
dfs(i, 0)
22+
23+
for i in range(len(l)):
24+
for j in l[i]:
25+
if color[i] == color[j]:
26+
return False
27+
28+
return True
29+
30+
31+
# Adjacency list of graph
32+
l = {0:[1,3], 1:[0,2], 2:[1,3], 3:[0,2], 4: []}
33+
print(check_bipartite_dfs(l))

0 commit comments

Comments
 (0)