int n=graph.size();

    vector<int> color(n,0);
    
    for(int i=0;i<n;i++)
    {
       
        if(color[i]==0)
            color[i]=1; // if not visited..
        
        queue<int> q1;
        
        q1.push(i);
        
        while(!q1.empty())
            
        {
            int a=q1.front();
            q1.pop();
            
            for(int j=0;j<graph[a].size();j++)
            {
                if(color[graph[a][j]]==0) //if not visited then change color
                {
                    color[graph[a][j]]=-1*color[a];
                    q1.push(graph[a][j]);
                }
                else if(color[graph[a][j]]==color[a])//if both color are same it will not bipartite.
                    return 0;
            }
        }
    }
    

if you like ,please upvote.

Comments (0)