Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.
Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex in V, there are no edges between vertices within the same set.
The graph is not bipartite because no matter how we try to color the nodes using two colors, there exists a cycle of odd length (like 1–2–0–1), which leads to a situation where two adjacent nodes end up with the same color. This violates the bipartite condition, which requires that no two connected nodes share the same color.
The given graph can be colored in two colors so, it is a bipartite graph.
In the previous post, we have discussed a BFS approach. In this post, we will cover the DFS approach.
Approach: Using Depth-First Search - O(V+E) Time and O(V) Space
To check if a graph is bipartite using Depth-First Search (DFS), we need to color the graph with two colors such that no two adjacent vertices share the same color. We start from any uncolored vertex, assigning it a color (e.g., color 0). As we explore each vertex, we recursively color its uncolored neighbors with the another color. If we ever find a neighbor that shares the same color as the current vertex, we can simply conclude that the graph is not bipartite. If there is no conflict found after the traversal then the given graph is bipartite.
Step-by-step approach:
Create a colors array where all vertices are initialized to -1 (uncolored).
Iterate through all vertices and for each vertex, if it is uncolored, start a DFS from that vertex.
Assign a color (0 or 1) to the current vertex.
Visit all adjacent vertices, if its color is same as current vertex, return false (not bipartite), otherwise assign opposite color and continue DFS.
If all vertices can be colored without conflicts, return true (graph is bipartite).
Output
true
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges. This is because DFS explores each vertex and edge exactly once. Auxiliary Space: O(V), for color array and recursion call stack, We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.