Given an undirected graph, determine whether it is bipartite using DFS. A bipartite graph (or bigraph) is a graph whose vertices can be divided into two disjoint sets U and V such that every edge connects a vertex in U to one in V.

The following is a bipartite graph as we can divide it into two sets, U and V, with every edge having one endpoint in set U and the other in set V:

 
Bipartite graph using DFS

Practice this problem

It is possible to test whether a graph is bipartite or not using a Depth–first search (DFS) algorithm. There are two ways to check for bipartite graphs:

  1. A graph is bipartite if and only if it is 2–colorable.
  2. A graph is bipartite if and only if it does not contain an odd cycle.

In the previous post, we have checked if the graph contains an odd cycle or not using BFS. Now using DFS, we will determine if the graph is 2–colorable or not.

The main idea is to assign each vertex a color that differs from its parent’s color in the depth–first search tree. If there exists an edge connecting the current vertex to a previously colored vertex with the same color, then we can say that the graph is not bipartite.

 
This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Graph is not bipartite

Java


Download  Run Code

Output:

Graph is not bipartite

Python


Download  Run Code

Output:

Graph is not bipartite

The time complexity of the above solution is O(V + E), where V and E are the total number of vertices and edges in the graph, respectively. Please note that O(E) may vary between O(1) and O(V2), depending on how dense the graph is.

 
References: Bipartite graph – Wikipedia