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).
C++
//Driver Code Starts#include<bits/stdc++.h>usingnamespacestd;vector<vector<int>>constructadj(intV,vector<vector<int>>&edges){vector<vector<int>>adj(V);for(autoit:edges){adj[it[0]].push_back(it[1]);adj[it[1]].push_back(it[0]);}returnadj;}//Driver Code Ends// Helper function for DFS to check bipartite graphbooldfs(intu,intcolor,vector<int>&colors,vector<vector<int>>&adj){// Assign color to the current ucolors[u]=color;// Iterate through all adjacent verticesfor(auto&v:adj[u]){if(colors[v]==-1){// Assign alternate color to the adjacent uif(!dfs(v,1-color,colors,adj))returnfalse;}elseif(colors[v]==color){// If the adjacent u has the same color,// it's not bipartitereturnfalse;}}returntrue;}// Function to check if the graph is Bipartite using DFSboolisBipartite(intV,vector<vector<int>>&edges){// Initialize all vertices as uncoloredvector<int>colors(V,-1);// create adjacency listvector<vector<int>>adj=constructadj(V,edges);// Check each component of the graphfor(inti=0;i<V;i++){// If the vertex is uncoloredif(colors[i]==-1){// If DFS fails, the graph is not bipartiteif(!dfs(i,0,colors,adj))returnfalse;}}// All vertices can be colored bipartitelyreturntrue;}//Driver Code Startsintmain(){intV=4;vector<vector<int>>edges={{0,1},{0,2},{1,2},{2,3}};if(isBipartite(V,edges))cout<<"true";elsecout<<"false";return0;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.*;classGfG{// Function to construct the adjacency list from edgesstaticArrayList<ArrayList<Integer>>constructadj(intV,int[][]edges){ArrayList<ArrayList<Integer>>adj=newArrayList<>();for(inti=0;i<V;i++){adj.add(newArrayList<>());}for(int[]edge:edges){intu=edge[0];intv=edge[1];adj.get(u).add(v);adj.get(v).add(u);}returnadj;}//Driver Code Ends// Helper function for DFS to check bipartite graphstaticbooleandfs(intu,intcolor,int[]colors,ArrayList<ArrayList<Integer>>adj){// Assign color to the current ucolors[u]=color;// Iterate through all adjacent verticesfor(intv:adj.get(u)){if(colors[v]==-1){// Assign alternate color to the adjacent uif(!dfs(v,1-color,colors,adj))returnfalse;}elseif(colors[v]==color){// If the adjacent u has the same color,// it's not bipartitereturnfalse;}}returntrue;}// Function to check if the graph is Bipartite using DFSstaticbooleanisBipartite(intV,int[][]edges){// Initialize all vertices as uncoloredint[]colors=newint[V];Arrays.fill(colors,-1);// create adjacency listArrayList<ArrayList<Integer>>adj=constructadj(V,edges);// Check each component of the graphfor(inti=0;i<V;i++){// If the vertex is uncoloredif(colors[i]==-1){// If DFS fails, the graph is not bipartiteif(!dfs(i,0,colors,adj))returnfalse;}}// All vertices can be colored bipartitelyreturntrue;}//Driver Code Startspublicstaticvoidmain(String[]args){intV=4;// Edges of the graphint[][]edges={{0,1},{0,2},{1,2},{2,3}};// Check if the graph is bipartiteSystem.out.println(isBipartite(V,edges));}}//Driver Code Ends
Python
#Driver Code Starts# Function to construct the adjacency list from edgesdefconstructadj(V,edges):adj=[[]for_inrange(V)]foredgeinedges:u,v=edgeadj[u].append(v)adj[v].append(u)returnadj#Driver Code Endsdefdfs(u,color,colors,adj):# Assign color to the current ucolors[u]=color# Iterate through all adjacent verticesforvinadj[u]:ifcolors[v]==-1:# Assign alternate color to the adjacent uifnotdfs(v,1-color,colors,adj):returnFalseelifcolors[v]==color:# If the adjacent u has the same color, it's not bipartitereturnFalsereturnTruedefisBipartite(V,edges):# Initialize all vertices as uncoloredcolors=[-1]*V# create adjacency listadj=constructadj(V,edges)# Check each component of the graphforiinrange(V):# If the vertex is uncoloredifcolors[i]==-1:# If DFS fails, the graph is not bipartiteifnotdfs(i,0,colors,adj):returnFalse# All vertices can be colored bipartitelyreturnTrue#Driver Code Startsif__name__=="__main__":V=4edges=[[0,1],[0,2],[1,2],[2,3]]print("true"ifisBipartite(V,edges)else"false")#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGfG{publicstaticList<List<int>>constructadj(intV,List<List<int>>edges){List<List<int>>adj=newList<List<int>>();for(inti=0;i<V;i++)adj.Add(newList<int>());foreach(varedgeinedges){intu=edge[0];intv=edge[1];adj[u].Add(v);adj[v].Add(u);}returnadj;}//Driver Code Ends// Helper function for DFS to check bipartite graphstaticbooldfs(intu,intcolor,int[]colors,List<List<int>>adj){// Assign color to the current ucolors[u]=color;// Iterate through all adjacent verticesforeach(intvinadj[u]){if(colors[v]==-1){// Assign alternate color to the adjacent uif(!dfs(v,1-color,colors,adj))returnfalse;}elseif(colors[v]==color){// If the adjacent u has the same color,// it's not bipartitereturnfalse;}}returntrue;}// Function to check if the graph is Bipartite using DFSstaticboolIsBipartite(intV,List<List<int>>edges){// Initialize all vertices as uncoloredint[]colors=newint[V];Array.Fill(colors,-1);// create adjacency listList<List<int>>adj=constructadj(V,edges);// Check each component of the graphfor(inti=0;i<V;i++){// If the vertex is uncoloredif(colors[i]==-1){// If DFS fails, the graph is not bipartiteif(!dfs(i,0,colors,adj))returnfalse;}}// All vertices can be colored bipartitelyreturntrue;}//Driver Code StartspublicstaticvoidMain(){intV=4;List<List<int>>edges=newList<List<int>>{newList<int>{0,1},newList<int>{0,2},newList<int>{1,2},newList<int>{2,3}};if(IsBipartite(V,edges))Console.WriteLine("true");elseConsole.WriteLine("false");}}//Driver Code Ends
JavaScript
//Driver Code Starts// Function to construct adjacency list from edgesfunctionconstructadj(V,edges){constadj=Array.from({length:V},()=>[]);for(const[u,v]ofedges){adj[u].push(v);adj[v].push(u);// undirected graph}returnadj;}//Driver Code Endsfunctiondfs(u,color,colors,adj){// Assign color to the current ucolors[u]=color;// Iterate through all adjacent verticesfor(letvofadj[u]){if(colors[v]===-1){// Assign alternate color to the adjacent uif(!dfs(v,1-color,colors,adj))returnfalse;}elseif(colors[v]===color){// If the adjacent u has the same color, it's// not bipartitereturnfalse;}}returntrue;}// Function to check if the graph is Bipartite using DFSfunctionisBipartite(V,edges){// Initialize all vertices as uncoloredconstcolors=Array(V).fill(-1);// create adjacency listletadj=constructadj(V,edges);// Check each component of the graphfor(leti=0;i<V;i++){// If the vertex is uncoloredif(colors[i]===-1){// If DFS fails, the graph is not bipartiteif(!dfs(i,0,colors,adj))returnfalse;}}// All vertices can be colored bipartitelyreturntrue;}//Driver Code StartsconstV=4;constadj=Array.from({length:V},()=>[]);letedges=[[0,1],[0,2],[1,2],[2,3]];console.log(isBipartite(V,edges));//Driver Code Ends
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.