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.
Checking if a graph is bipartite is like trying to color the graph using only two colors, so that no two adjacent vertices have the same color. One approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring problem.
A common and efficient way to solve this is by using Breadth-First Search (BFS). The idea is to traverse the graph level by level and assign colors alternately to the vertices as we proceed.
Step-by-step approach:
Start BFS from any uncolored vertex and assign it color 0.
For each vertex, color its uncolored neighbors with the opposite color (1 if current is 0, and vice versa)
Check if a neighbor already has the same color as the current vertex, return false (graph is not bipartite).
If BFS completes without any conflicts, return true (graph is bipartite).
Below is the implementation of the above approach:
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;}// Function to check if the graph is Bipartite using BFS//Driver Code EndsboolisBipartite(intV,vector<vector<int>>&edges){// Vector to store colors of vertices.// Initialize all as -1 (uncolored)vector<int>color(V,-1);//create adjacency listvector<vector<int>>adj=constructadj(V,edges);// 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 bipartite//Driver Code Startsreturntrue;}intmain(){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;}// Function to check if the graph is Bipartite using BFS//Driver Code EndsstaticbooleanisBipartite(intV,int[][]edges){int[]color=newint[V];Arrays.fill(color,-1);// create adjacency listArrayList<ArrayList<Integer>>adj=constructadj(V,edges);for(inti=0;i<V;i++){if(color[i]==-1){Queue<Integer>q=newLinkedList<>();color[i]=0;q.offer(i);while(!q.isEmpty()){intu=q.poll();for(intv:adj.get(u)){if(color[v]==-1){color[v]=1-color[u];q.offer(v);}elseif(color[v]==color[u]){returnfalse;// Conflict found}}}}//Driver Code Starts}returntrue;}publicstaticvoidmain(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 Startsfromcollectionsimportdeque# 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# Function to check if the graph is Bipartite using BFS#Driver Code EndsdefisBipartite(V,adj):# Initialize all as uncoloredcolor=[-1]*V# create adjacency listadj=constructadj(V,edges)foriinrange(V):ifcolor[i]==-1:color[i]=0q=deque([i])whileq:u=q.popleft()forvinadj[u]:ifcolor[v]==-1:color[v]=1-color[u]q.append(v)elifcolor[v]==color[u]:returnFalse# Conflict found#Driver Code Starts# No conflict, graph is bipartitereturnTrueif__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// Function to check if the graph is Bipartite using BFSpublicstaticboolIsBipartite(intV,List<List<int>>edges){int[]color=newint[V];// create adjacency listList<List<int>>adj=constructadj(V,edges);// Initialize all as -1 (uncolored)Array.Fill(color,-1);// 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)color[i]=0;Queue<int>q=newQueue<int>();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 bipartite//Driver Code Startsreturntrue;}staticvoidMain(){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 EndsfunctionisBipartite(V,edges){// Initialize all as -1 (uncolored)constcolor=Array(V).fill(-1);// create adjacency listletadj=constructadj(V,edges);// 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)color[i]=0;constqueue=[i];// Perform BFSwhile(queue.length>0){constu=queue.shift();// Traverse all adjacent verticesfor(letvofadj[u]){// If the adjacent vertex is uncolored,// assign alternate colorif(color[v]===-1){color[v]=1-color[u];queue.push(v);// Push to queue}// If the adjacent vertex has the same// color, graph is not bipartiteelseif(color[v]===color[u]){returnfalse;}}}}}// If no conflicts in coloring, graph is bipartite//Driver Code Startsreturntrue;}// Driver CodeconstV=4;constadj=Array.from({length:V},()=>[]);letedges=[[0,1],[0,2],[1,2],[2,3]];console.log(isBipartite(V,edges));//Driver Code Ends
Output
false
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges. This is because BFS explores each vertex and edge exactly once. Auxiliary Space: O(V), The queue used in BFS, which can hold up to V vertices and The color array (or map), which stores the color for each vertex, We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.
Using Depth-First Search (DFS)
We can also 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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.