Bipartite Graph | Practice | GeeksforGeeks

Given an adjacency list of a graph adj  of V no. of vertices having 0 based index. Check whether the graph is bipartite or not.
 
Example 1:
Input: 

Output: 1
Explanation: The given graph can be colored 
in two colors so, it is a bipartite graph.

Example 2:
Input:

Output: 0
Explanation: The given graph cannot be colored 
in two colors such that color of adjacent 
vertices differs. 

 
Your Task:
You don't need to read or print anything. Your task is to complete the function isBipartite() which takes V denoting no. of vertices and adj denoting adjacency list of the graph and returns a boolean value true if the graph is bipartite otherwise returns false.
 
Expected Time Complexity: O(V + E)
Expected Space Complexity: O(V)

Constraints:
1 ≤ V, E ≤ 105
0
lilith6 days ago
Java Code :
class Solution
{
    class Pair {
        int v, level;
        
        Pair (int v, int level) {
            this.v = v;
            this.level = level;
        }
    }
    
    public boolean isBipartite(int V, ArrayList<ArrayList<Integer>>adj)
    {
        // Code here
        int[] visited = new int[V];
        Arrays.fill(visited, -1);
        
        for(int i = 0; i < V; i++) {
            if(visited[i] == - 1)
                if(!findBipartite(adj, i, visited))
                    return false;
        }
        
        return true;
    }
    
    public boolean findBipartite(ArrayList<ArrayList<Integer>> graph, int source, int[] visited) {
        ArrayDeque<Pair> q = new ArrayDeque<>();
        q.add(new Pair(source,0));
        
        while(!q.isEmpty()) {
            Pair rem = q.remove();
            
            if(visited[rem.v] != -1) {
                if(visited[rem.v] != rem.level)
                    return false;
            } else 
                visited[rem.v] = rem.level;
            
            for(int e : graph.get(rem.v)) {
                if(visited[e] == -1) {
                    q.add(new Pair(e, rem.level + 1));
                }
            }
        }
        
        return true;
    }
}
0
ajaynikumbh1 week ago
class Solution
{
public:

    bool bipartitate_check(int src,vector<int> adj[], vector<int> &color )
    {
        // If the color of src == -1 color it
        if(color[src] == -1) color[src] =1;
        
        // Travel through it's nbrs
        for(auto it: adj[src])
        {
            // If the color == -1 of it's nbrs then color
            if(color[it] == -1)
            {
                color[it] = 1- color[src];
                
                // Call the dfs again
                if(!bipartitate_check(it, adj, color))
                return false;
            }
            
            // If the color of src and nbr is same return false
            else if(color[it] == color[src]) return false;
        }
        
        // Return true if different color
        return true;
    }


	bool isBipartite(int v, vector<int>adj[])
	{
	    // Declare the color array
	    vector<int> color(v, -1);
	    
	    // Travel for each components
	    for(int i=0;i<v;i++)
	    {
	        // If the color[i] is -1 then call check bipartiate graph function 
	        if(color[i] == -1)
	        {
	            
	            if(!bipartitate_check(i,adj,color)) return false;
	        }
	    }
	    return true;
	}

};
+2
ajaynikumbh1 week ago
class Solution
{
public:

    bool bipartitate_check(int src,vector<int> adj[], vector<int> &color )
    {
        // Make a queue
        queue<int> q;
        
        // Push the src node
        q.push(src);
        
        // Color the src node with 1
        color[src] =1;
        
        // Travel till queue not empty
        while(!q.empty())
        {
            // Extract the front node
            int node= q.front();
            q.pop();
            
            // Explore the nodes of the front node
            for(auto it: adj[node])
            {
                // If the nbrs color == -1 then color them 
                // with the different color
                if(color[it] == -1)
                {
                    
                    color[it] = 1- color[node];
                    q.push(it);
                }
                
                // If the scr node and curr node same color return false
                else if(color[it] == color[node]) return false;
                
            }
        }
        return true;
    }


	bool isBipartite(int v, vector<int>adj[])
	{
	    // Declare the color array
	    vector<int> color(v, -1);
	    
	    // Travel for each components
	    for(int i=0;i<v;i++)
	    {
	        // If the color[i] is -1 then call check bipartiate graph function 
	        if(color[i] == -1)
	        {
	            
	            if(!bipartitate_check(i,adj,color)) return false;
	        }
	    }
	    return true;
	}

};
+1
bhaskarmaheshwari84 weeks ago
using dfs
//refer https://www.youtube.com/watch?v=nbgaEu-pvkU   bool isBipartiteUtil(int node,vector<int>adj[],vector<int>&color,int prev)   {           if(prev!=-1)           color[node]=1-color[prev];           else            color[node]=1;         vector<int>::iterator itr;           for(itr=adj[node].begin();itr!=adj[node].end();itr++)           {               if(color[*itr]==-1)               {                   if(!isBipartiteUtil(*itr,adj,color,node))                   {                       return 0;                   }               }               else if(color[*itr]==color[node])// not this imp(color[*itr]==color[prev])               return 0;           }       return 1;   }bool isBipartite(int V, vector<int>adj[]){    // Code here    vector<int> color(V,-1);    int prev=-1;     for(int i=0;i<V;i++)     {         if(color[i]==-1)         {             if(!isBipartiteUtil(i,adj,color,prev))             return 0;         }     }     return 1;} 
+1
bhaskarmaheshwari84 weeks ago
//refer https://www.youtube.com/watch?v=nbgaEu-pvkU   bool isBipartiteUtil(int src,vector<int>adj[],vector<int>&color)   {       queue<int> q;       q.push(src);       color[src]=1;       while(!q.empty())       {           int node=q.front();           q.pop();           vector<int>::iterator itr;           for(itr=adj[node].begin();itr!=adj[node].end();itr++)           {               if(color[*itr]==-1)               {                   color[*itr]=1-color[node];                   q.push(*itr);               }               else if(color[node]==color[*itr])               return 0;           }                  }       return 1;   }bool isBipartite(int V, vector<int>adj[]){    // Code here    vector<int> color(V,-1);     for(int i=0;i<V;i++)     {         if(color[i]==-1)         {             if(!isBipartiteUtil(i,adj,color))             return 0;         }     }     return 1;} 
0
mbi20210121 month ago
// using BFS
bool isBipartite(int V, vector<int>adj[]){           vector<int>vis(V,-1);        for(int i=0; i<V; i++)    {                queue<int>q;    q.push(i);    vis[0]=0;        while(!q.empty())    {        int node = q.front();        q.pop();        for(auto it: adj[node])        {                    if(vis[it]==-1)          {               q.push(it);              if(vis[node]==0)              {                  vis[it]=1;              }                            else              {                  vis[it]=0;              }          }                    else          {              if(vis[it]==vis[node])              {                  return false;              }                        }                  }            }    }        return true;
0
imaniket1 month ago
DFS | Bipartition Check | C++ 
bool dfs(int i, int prev, vector<int> adj[], vector<int> &color){
        color[i] = color[prev]==1 ? 0 : 1;
        for(auto it: adj[i]){
            if(color[it]==-1){
                if(!dfs(it, i, adj, color)) return false;
            }
            else if(color[it]==color[i]) return false;
        }
        return true;
    }
	bool isBipartite(int V, vector<int>adj[]){
	   vector<int> color(V, -1);
	   for(int i=0; i<V; i++){
	       if(color[i]==-1){
	           if(!dfs(i, -1, adj, color)) return false;
	       }
	   }
	   return true;
	}
+1
forcer1 month ago
bool solve(int n,vector<int> adj[],vector<bool>&vis,vector<int>&color)
{   
    color[n]=1;
    vis[n]=true;
    queue<int>q;
    q.push(n);
    while(!q.empty())
    {
        int node=q.front();
        q.pop();
        for(auto it:adj[node])
        {
            if(color[it]==-1)
            {
                vis[it]=true;
                color[it]=!color[node];
                q.push(it);
                
            }
            else if(color[it]==color[node]) return false;
        }
    }
    return true;
    
}
	bool isBipartite(int V, vector<int>adj[])
	{
	    vector<bool>vis(V,false);
	    vector<int>color(V,-1);
	    for(int i=0;i<V;i++)
	    {   
	        if(!vis[i])
	        {
	        if(!solve(i,adj,vis,color)) 
	        return false;
	        }
	    }
	    return true;
	}
0
avnyaswanth1 month ago
int col[100000];   bool vis[100000];   bool dfs(int ver, vector<int> graph[], int c)   {       vis[ver] = 1;       col[ver] = c;       for(auto adjnode : graph[ver])       {           if(vis[adjnode] == 0)           {               if(dfs(ver, graph, c ^ 1) == false)                   return false;           }                      else if(col[adjnode] == col[ver])               return false;       }              return true;   }bool isBipartite(int V, vector<int> graph[]){    memset(col, -1, sizeof(col));       memset(vis, 0, sizeof(vis));       int v = V;       for(int i=0;i<v;++i)       {           if(!vis[i])           {               if(dfs(i, graph, 0) == false)                   return false;           }       }       return true;}
 
 
// i am getting run time error for this code. Can any one tell me where i am doing the mistake?
0
detroix071 month ago
bool helper(int source,vector<int> adj[],vector<int> &color) {          if(color[source]==-1)  color[source] = 2;            for(auto children : adj[source]) {        if(color[children] == -1) {         color[children] = -color[source];         if(!helper(children,adj,color)) return false;        } else {          if(color[children]==color[source]) return false;        }      }    return true; }  bool isBipartite(int V, vector<int>adj[]) {vector<int> color(V,-1);for(int i=0;i<V;i++) { if(color[i]==-1) {   bool output = helper(i,adj,color);   if(output==false) return false; }}  return true; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.