From 029679ee619a9b81bc0cb652484adeefb68a3296 Mon Sep 17 00:00:00 2001 From: Erfan Alimohammadi Date: Tue, 14 May 2019 18:31:32 +0430 Subject: [PATCH] Implement check_bipartite_graph using DFS. --- graphs/check_bipartite_graph_dfs.py | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 graphs/check_bipartite_graph_dfs.py diff --git a/graphs/check_bipartite_graph_dfs.py b/graphs/check_bipartite_graph_dfs.py new file mode 100644 index 000000000000..eeb3a84b7a15 --- /dev/null +++ b/graphs/check_bipartite_graph_dfs.py @@ -0,0 +1,33 @@ +# Check whether Graph is Bipartite or Not using DFS + +# A Bipartite Graph is a graph whose vertices can be divided into two independent sets, +# U and V such that every edge (u, v) either connects a vertex from U to V or a vertex +# from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, +# or u belongs to V and v to U. We can also say that there is no edge that connects +# vertices of same set. +def check_bipartite_dfs(l): + visited = [False] * len(l) + color = [-1] * len(l) + + def dfs(v, c): + visited[v] = True + color[v] = c + for u in l[v]: + if not visited[u]: + dfs(u, 1 - c) + + for i in range(len(l)): + if not visited[i]: + dfs(i, 0) + + for i in range(len(l)): + for j in l[i]: + if color[i] == color[j]: + return False + + return True + + +# Adjacency list of graph +l = {0:[1,3], 1:[0,2], 2:[1,3], 3:[0,2], 4: []} +print(check_bipartite_dfs(l))