Given an undirected graph represented by an adjacency list adj[][], check whether the graph is bipartite or not.
A bipartite graph is a graph whose vertices can be colored using two colors such that no two adjacent vertices have the same color. Equivalently, the vertices can be divided into two disjoint sets such that:
Every edge connects a vertex from one set to a vertex in the other set.
No edge connects two vertices within the same set.
Examples:
Input:adj[][] = [[1], [0, 2], [1]]
Output: true Explanation: The vertices can be colored using two colors such that every pair of adjacent vertices has different colors.
Input:adj[][] = [[2, 3], [2], [0, 1, 3], [0, 2]]
Output: false Explanation: The vertices form a triangle, so it is not possible to color them using two colors without two adjacent vertices having the same color.
[Naive Approach] Backtracking - O(2^V Ã (V + E)) Time and O(V) Space
The idea is to recursively assign one of the two colors to every vertex. Before assigning a color, check whether any adjacent vertex already has the same color. If no valid coloring is possible after trying both colors, the graph is not bipartite.
Working of Approach:
Create an adjacency list from the given edges.
Recursively assign either color 0 or 1 to every uncolored vertex.
Before assigning a color, ensure that none of its adjacent vertices has the same color.
If a color leads to a conflict, backtrack and try the other color.
If all vertices are colored successfully, return true; otherwise, return false.
C++
#include<iostream>#include<vector>usingnamespacestd;boolisSafe(intnode,intclr,vector<int>&color,vector<vector<int>>&adj){// Check all adjacent vertices.for(intneigh:adj[node]){if(color[neigh]==clr)returnfalse;}returntrue;}boolsolve(intnode,intV,vector<int>&color,vector<vector<int>>&adj){// All vertices are colored.if(node==V)returntrue;// Skip already colored vertices.if(color[node]!=-1)returnsolve(node+1,V,color,adj);// Try both colors.for(intclr=0;clr<=1;clr++){if(isSafe(node,clr,color,adj)){// Assign color.color[node]=clr;// Recur for next vertex.if(solve(node+1,V,color,adj))returntrue;// Backtrack.color[node]=-1;}}returnfalse;}boolisBipartite(vector<vector<int>>&adj){intV=adj.size();// -1 means vertex is uncolored.vector<int>color(V,-1);returnsolve(0,V,color,adj);}intmain(){vector<vector<int>>adj={{1},{0,2},{1}};if(isBipartite(adj))cout<<"true";elsecout<<"false";return0;}
Java
importjava.util.*;classGFG{staticbooleanisSafe(intnode,intclr,int[]color,ArrayList<ArrayList<Integer>>adj){// Check all adjacent vertices.for(intneigh:adj.get(node)){if(color[neigh]==clr)returnfalse;}returntrue;}staticbooleansolve(intnode,intV,int[]color,ArrayList<ArrayList<Integer>>adj){// All vertices are colored.if(node==V)returntrue;// Skip already colored vertices.if(color[node]!=-1)returnsolve(node+1,V,color,adj);// Try both colors.for(intclr=0;clr<=1;clr++){if(isSafe(node,clr,color,adj)){// Assign color.color[node]=clr;// Recur for next vertex.if(solve(node+1,V,color,adj))returntrue;// Backtrack.color[node]=-1;}}returnfalse;}staticbooleanisBipartite(ArrayList<ArrayList<Integer>>adj){intV=adj.size();// -1 means vertex is uncolored.int[]color=newint[V];Arrays.fill(color,-1);returnsolve(0,V,color,adj);}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>adj=newArrayList<>();adj.add(newArrayList<>(Arrays.asList(1)));adj.add(newArrayList<>(Arrays.asList(0,2)));adj.add(newArrayList<>(Arrays.asList(1)));System.out.println(isBipartite(adj)?"true":"false");}}
Python
defisSafe(node,clr,color,adj):# Check all adjacent vertices.forneighinadj[node]:ifcolor[neigh]==clr:returnFalsereturnTruedefsolve(node,V,color,adj):# All vertices are colored.ifnode==V:returnTrue# Skip already colored vertices.ifcolor[node]!=-1:returnsolve(node+1,V,color,adj)# Try both colors.forclrinrange(2):ifisSafe(node,clr,color,adj):# Assign color.color[node]=clr# Recur for next vertex.ifsolve(node+1,V,color,adj):returnTrue# Backtrack.color[node]=-1returnFalsedefisBipartite(adj):V=len(adj)# -1 means vertex is uncolored.color=[-1]*Vreturnsolve(0,V,color,adj)# Driver Codeif__name__=="__main__":adj=[[1],[0,2],[1]]print(str(isBipartite(adj)).lower())
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticboolisSafe(intnode,intclr,int[]color,List<List<int>>adj){// Check all adjacent vertices.foreach(intneighinadj[node]){if(color[neigh]==clr)returnfalse;}returntrue;}staticboolsolve(intnode,intV,int[]color,List<List<int>>adj){// All vertices are colored.if(node==V)returntrue;// Skip already colored vertices.if(color[node]!=-1)returnsolve(node+1,V,color,adj);// Try both colors.for(intclr=0;clr<=1;clr++){if(isSafe(node,clr,color,adj)){// Assign color.color[node]=clr;// Recur for next vertex.if(solve(node+1,V,color,adj))returntrue;// Backtrack.color[node]=-1;}}returnfalse;}// Function to check if graph is bipartite.staticboolisBipartite(List<List<int>>adj){intV=adj.Count;// -1 means vertex is uncolored.int[]color=newint[V];Array.Fill(color,-1);returnsolve(0,V,color,adj);}staticvoidMain(){List<List<int>>adj=newList<List<int>>{newList<int>{1},newList<int>{0,2},newList<int>{1}};Console.WriteLine(isBipartite(adj)?"true":"false");}}
JavaScript
functionisSafe(node,clr,color,adj){// Check all adjacent vertices.for(letneighofadj[node]){if(color[neigh]===clr)returnfalse;}returntrue;}functionsolve(node,V,color,adj){// All vertices are colored.if(node===V)returntrue;// Skip already colored vertices.if(color[node]!==-1)returnsolve(node+1,V,color,adj);// Try both colors.for(letclr=0;clr<=1;clr++){if(isSafe(node,clr,color,adj)){// Assign color.color[node]=clr;// Recur for next vertex.if(solve(node+1,V,color,adj))returntrue;// Backtrack.color[node]=-1;}}returnfalse;}functionisBipartite(adj){letV=adj.length;// -1 means vertex is uncolored.letcolor=newArray(V).fill(-1);returnsolve(0,V,color,adj);}// Driver Codeletadj=[[1],[0,2],[1]];console.log(isBipartite(adj));
Output
true
Time Complexity: O(2^V Ã (V + E)), since each vertex can be assigned one of two colors, and every assignment checks adjacent vertices. Space Complexity: O(V), The color array and recursion stack require O(V) space.
[Expected Approach] BFS Traversal - O(V + E) Time and O(V) Space
The idea is to perform a BFS traversal and color each vertex with one of two colors. Every adjacent vertex is assigned the opposite color. If two adjacent vertices are found with the same color, the graph is not bipartite.
Working of Approach:
Create an adjacency list from the given edges.
Start BFS from every unvisited vertex to handle disconnected graphs.
Assign the starting vertex color 0 and color every neighbor with the opposite color.
If an already colored neighbor has the same color as the current vertex, return false.
If BFS finishes without any conflict, return true.
Let us understand with an example: Input: adj[][] = [[1], [0, 2], [1]]
Initialize the color array as [-1, -1, -1] and start BFS from vertex 0.
Assign color 0 to vertex 0 and push it into the queue.
Visit vertex 1, assign it the opposite color 1, and push it into the queue.
Visit vertex 2 from vertex 1 and assign it color 0.
Every adjacent pair of vertices has different colors, so no conflict is found.
Therefore, the graph is bipartite, and the answer is true.
C++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;// Function to check if the graph is bipartite or notboolisBipartite(vector<vector<int>>&adj){intV=adj.size();// Vector to store colors of vertices.// Initialize all as -1 (uncolored)vector<int>color(V,-1);// Queue for BFSqueue<int>q;// Iterate through all vertices to handle disconnected graphsfor(inti=0;i<V;i++){// If the vertex is uncolored, start BFS from itif(color[i]==-1){// Assign first color (0) to the starting vertexcolor[i]=0;q.push(i);// Perform BFSwhile(!q.empty()){intu=q.front();q.pop();// Traverse all adjacent verticesfor(auto&v:adj[u]){// If the adjacent vertex is uncolored,// assign alternate colorif(color[v]==-1){color[v]=1-color[u];q.push(v);}// If the adjacent vertex has the same color,// graph is not bipartiteelseif(color[v]==color[u]){returnfalse;}}}}}// If no conflicts in coloring, graph is bipartitereturntrue;}intmain(){vector<vector<int>>adj={{1},{0,2},{1}};if(isBipartite(adj))cout<<"true";elsecout<<"false";return0;}
Java
importjava.util.Queue;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.LinkedList;classGFG{// Function to check if the graph is bipartite or notstaticbooleanisBipartite(ArrayList<ArrayList<Integer>>adj){intV=adj.size();// Vector to store colors of vertices.// Initialize all as -1 (uncolored)int[]color=newint[V];Arrays.fill(color,-1);// Queue for BFSQueue<Integer>q=newLinkedList<>();// Iterate through all vertices to handle disconnected graphsfor(inti=0;i<V;i++){// If the vertex is uncolored, start BFS from itif(color[i]==-1){// Assign first color (0) to the starting vertexcolor[i]=0;q.add(i);// Perform BFSwhile(!q.isEmpty()){intu=q.poll();// Traverse all adjacent verticesfor(intv:adj.get(u)){// If the adjacent vertex is uncolored,// assign alternate colorif(color[v]==-1){color[v]=1-color[u];q.add(v);}// If the adjacent vertex has the same color,// graph is not bipartiteelseif(color[v]==color[u]){returnfalse;}}}}}// If no conflicts in coloring, graph is bipartitereturntrue;}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>adj=newArrayList<>();adj.add(newArrayList<>(Arrays.asList(1)));adj.add(newArrayList<>(Arrays.asList(0,2)));adj.add(newArrayList<>(Arrays.asList(1)));System.out.println(isBipartite(adj));}}
Python
fromcollectionsimportdeque# Function to check if the graph is bipartite or notdefisBipartite(adj):V=len(adj)# List to store colors of vertices.# Initialize all as -1 (uncolored)color=[-1]*V# Queue for BFSq=deque()# Iterate through all vertices to handle disconnected graphsforiinrange(V):# If the vertex is uncolored, start BFS from itifcolor[i]==-1:# Assign first color (0) to the starting vertexcolor[i]=0q.append(i)# Perform BFSwhileq:u=q.popleft()# Traverse all adjacent verticesforvinadj[u]:# If the adjacent vertex is uncolored,# assign alternate colorifcolor[v]==-1:color[v]=1-color[u]q.append(v)# If the adjacent vertex has the same color,# graph is not bipartiteelifcolor[v]==color[u]:returnFalse# If no conflicts in coloring, graph is bipartitereturnTrue# Driver Codeif__name__=='__main__':adj=[[1],[0,2],[1]]ifisBipartite(adj):print('true')else:print('false')
C#
usingSystem;usingSystem.Collections.Generic;publicclassGFG{publicstaticboolisBipartite(List<List<int>>adj){intV=adj.Count;// List to store colors of vertices.// Initialize all as -1 (uncolored)int[]color=newint[V];for(inti=0;i<V;i++){color[i]=-1;}// Queue for BFSQueue<int>q=newQueue<int>();// Iterate through all vertices to handle// disconnected graphsfor(inti=0;i<V;i++){// If the vertex is uncolored, start BFS from itif(color[i]==-1){// Assign first color (0) to the starting// vertexcolor[i]=0;q.Enqueue(i);// Perform BFSwhile(q.Count>0){intu=q.Dequeue();// Traverse all adjacent verticesforeach(intvinadj[u]){// If the adjacent vertex is// uncolored, assign alternate colorif(color[v]==-1){color[v]=1-color[u];q.Enqueue(v);}// If the adjacent vertex has the// same color, graph is not// bipartiteelseif(color[v]==color[u]){returnfalse;}}}}}// If no conflicts in coloring, graph is bipartitereturntrue;}publicstaticvoidMain(){List<List<int>>adj=newList<List<int>>{newList<int>{1},newList<int>{0,2},newList<int>{1}};if(isBipartite(adj))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Function to check if the graph is bipartite or notfunctionisBipartite(adj){letV=adj.length;// Vector to store colors of vertices.// Initialize all as -1 (uncolored)letcolor=newArray(V).fill(-1);// Queue for BFSletq=[];// Iterate through all vertices to handle disconnected// graphsfor(leti=0;i<V;i++){// If the vertex is uncolored, start BFS from itif(color[i]===-1){// Assign first color (0) to the starting vertexcolor[i]=0;q.push(i);// Perform BFSwhile(q.length>0){letu=q.shift();// Traverse all adjacent verticesfor(letvofadj[u]){// If the adjacent vertex is uncolored,// assign alternate colorif(color[v]===-1){color[v]=1-color[u];q.push(v);}// If the adjacent vertex has the same// color, graph is not bipartiteelseif(color[v]===color[u]){returnfalse;}}}}}// If no conflicts in coloring, graph is bipartitereturntrue;}// Driver codeletadj=[[1],[0,2],[1]];console.log(isBipartite(adj));
Output
true
[Alternate Approach] DFS Traversal - O(V + E) Time and O(V) Space
The idea is to perform a DFS traversal and color each vertex with one of two colors. During DFS, every adjacent vertex is assigned the opposite color. If two adjacent vertices receive the same color, the graph is not bipartite.
Working of Approach:
Create an adjacency list from the given edges.
Start DFS from every unvisited vertex.
Assign alternate colors while visiting adjacent vertices.
If an adjacent vertex already has the same color, return false.
If all components are colored successfully, return true.
C++
#include<iostream>#include<vector>usingnamespacestd;// DFS function to color vertices.booldfs(intnode,intclr,vector<int>&color,vector<vector<int>>&adj){// Assign color to current vertex.color[node]=clr;// Visit all adjacent vertices.for(intneigh:adj[node]){// If the adjacent vertex is uncolored,// assign alternate color.if(color[neigh]==-1){if(!dfs(neigh,1-clr,color,adj))returnfalse;}// If the adjacent vertex has the same color,// graph is not bipartite.elseif(color[neigh]==clr){returnfalse;}}returntrue;}boolisBipartite(vector<vector<int>>&adj){intV=adj.size();// -1 means vertex is uncolored.vector<int>color(V,-1);// Traverse every connected component.for(inti=0;i<V;i++){if(color[i]==-1){if(!dfs(i,0,color,adj))returnfalse;}}returntrue;}intmain(){vector<vector<int>>adj={{1},{0,2},{1}};if(isBipartite(adj))cout<<"true";elsecout<<"false";return0;}
Java
importjava.util.ArrayList;importjava.util.Arrays;classGFG{staticbooleandfs(intnode,intclr,int[]color,ArrayList<ArrayList<Integer>>adj){// Assign color to current vertex.color[node]=clr;// Visit all adjacent vertices.for(intneigh:adj.get(node)){// If the adjacent vertex is uncolored,// assign alternate color.if(color[neigh]==-1){if(!dfs(neigh,1-clr,color,adj))returnfalse;}// If the adjacent vertex has the same color,// graph is not bipartite.elseif(color[neigh]==clr){returnfalse;}}returntrue;}staticbooleanisBipartite(ArrayList<ArrayList<Integer>>adj){intV=adj.size();// -1 means vertex is uncolored.int[]color=newint[V];Arrays.fill(color,-1);// Traverse every connected component.for(inti=0;i<V;i++){if(color[i]==-1){if(!dfs(i,0,color,adj))returnfalse;}}returntrue;}publicstaticvoidmain(String[]args){ArrayList<ArrayList<Integer>>adj=newArrayList<>();adj.add(newArrayList<>(Arrays.asList(1)));adj.add(newArrayList<>(Arrays.asList(0,2)));adj.add(newArrayList<>(Arrays.asList(1)));if(isBipartite(adj))System.out.print("true");elseSystem.out.print("false");}}
Python
# DFS function to color vertices.defdfs(node,clr,color,adj):# Assign color to current vertex.color[node]=clr# Visit all adjacent vertices.forneighinadj[node]:# If the adjacent vertex is uncolored,# assign alternate color.ifcolor[neigh]==-1:ifnotdfs(neigh,1-clr,color,adj):returnFalse# If the adjacent vertex has the same color,# graph is not bipartite.elifcolor[neigh]==clr:returnFalsereturnTruedefisBipartite(adj):V=len(adj)# -1 means vertex is uncolored.color=[-1]*V# Traverse every connected component.foriinrange(V):ifcolor[i]==-1:ifnotdfs(i,0,color,adj):returnFalsereturnTrue# Driver Codeif__name__=="__main__":adj=[[1],[0,2],[1]]ifisBipartite(adj):print("true")else:print("false")
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticbooldfs(intnode,intclr,int[]color,List<List<int>>adj){// Assign color to current vertex.color[node]=clr;// Visit all adjacent vertices.foreach(intneighinadj[node]){// If the adjacent vertex is uncolored,// assign alternate color.if(color[neigh]==-1){if(!dfs(neigh,1-clr,color,adj))returnfalse;}// If the adjacent vertex has the same color,// graph is not bipartite.elseif(color[neigh]==clr){returnfalse;}}returntrue;}staticboolisBipartite(List<List<int>>adj){intV=adj.Count;// -1 means vertex is uncolored.int[]color=newint[V];Array.Fill(color,-1);// Traverse every connected component.for(inti=0;i<V;i++){if(color[i]==-1){if(!dfs(i,0,color,adj))returnfalse;}}returntrue;}staticvoidMain(){List<List<int>>adj=newList<List<int>>{newList<int>{1},newList<int>{0,2},newList<int>{1}};if(isBipartite(adj))Console.Write("true");elseConsole.Write("false");}}
JavaScript
// DFS function to color vertices.functiondfs(node,clr,color,adj){// Assign color to current vertex.color[node]=clr;// Visit all adjacent vertices.for(letneighofadj[node]){// If the adjacent vertex is uncolored,// assign alternate color.if(color[neigh]===-1){if(!dfs(neigh,1-clr,color,adj))returnfalse;}// If the adjacent vertex has the same color,// graph is not bipartite.elseif(color[neigh]===clr){returnfalse;}}returntrue;}functionisBipartite(adj){letV=adj.length;// -1 means vertex is uncolored.letcolor=newArray(V).fill(-1);// Traverse every connected component.for(leti=0;i<V;i++){if(color[i]===-1){if(!dfs(i,0,color,adj))returnfalse;}}returntrue;}// Driver codeletadj=[[1],[0,2],[1]];if(isBipartite(adj))console.log("true");elseconsole.log("false");