Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Check Bipartite Graph

Moderate
0/80
Average time to solve is 50m
profile
Contributed by
85 upvotes
Asked in companies
UberWalmarteBay

Problem statement

Given a graph, check whether the graph is bipartite or not. Your function should return true if the given graph's vertices can be divided into two independent sets, ‘U’ and ‘V’ such that every edge (‘u’, ‘v’) either connects a vertex from ‘U’ to ‘V’ or a vertex from ‘V’ to ‘U’.

You are given a 2D array ‘edges’ which contains 0 and 1, where ‘edges[i][j]’ = 1 denotes a bi-directional edge from ‘i’ to ‘j’.

Note:
If edges[i][j] = 1, that implies there is a bi-directional edge between ‘i’ and ‘j’, that means there exists both edges from ‘i’ to ‘j’ and to ‘j’ to ‘i’.

For example

Given:
‘N’ = 3
‘edges’ = [[0, 1, 1], [0, 0, 1], [0,0,0]]. 

Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The first line of each test case contains two space-separated integers, ‘N,’ where ‘N’ is the number of rows in ‘edges’ and the number of columns in ‘edges’.

The next ‘N’ line of each test case contains ‘N’ space-separated integers which tell if there is an edge between ‘i’ and ‘j’.
Output Format :
For each test case, You are supposed to return a bool value determining whether the graph is bipartite or not.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= ‘T’ <= 10
2 <= ‘N’ <= 300
0 <= ‘edges[i][j]’ <= 1. 

Time Limit: 1sec.

Sample Input 1 :

2
4
0 1 0 0 
0 0 0 1 
0 0 0 0 
0 0 0 0 
3
0 1 1
0 0 1
0 0 0

Sample Output 1 :

1
0 

Explanation of the Sample Input 1:

In the first test case, the graph is visualized as below,

The graph can be divided into 2 disjointed sections, i.e. S1 = {0,2} and S2 = {1,3}. Therefore the answer is true.

In the second test case, the graph is visualized as below: 

The answer is 0 since there is no way this graph can be divided into 2 disjoint sets of points.

Sample Input 2 :

2
4
0 0 1 0 
0 0 0 1 
0 0 0 0 
0 0 0 0 
3
0 1 1
0 0 0 
0 0 0

Sample Output 2 :

1
1
Hint

Can we think of 2 sets as 2 different colors?

Approaches (1)
Breadth First Search

The idea is that a bipartite can be colored in such a way that only 2 colors in total would be used,  where the neighbor nodes have different colors. Therefore we can do a breadth-first search and assign colors to each vertex and if at any point neighboring nodes have the same color we return false.


 

The steps are as follows:

  • Parse the given ‘edges’ into an adjacency matrix ‘graph’, by pushing ‘i’ is graph[j] and ‘j’ in graph[i] if edges[i][j] is 1.
  • Maintain a vector ‘color’ which denotes the color of the ‘i’ the node, initially, all colors are un-assigned, hence -1.
  • Maintain a color ‘c’ initially 0 to assign to nodes and flip after each level of the graph.
  • Now maintain a queue ‘que’ for doing a breadth-first traversal and push ‘i’, the root node in it.
  • While ‘que’ is not empty:
    • Maintain a variable ‘node’ which denotes the node in the front of the ‘que’.
    • Traverse all the neighbors ‘nbr’ of the current node.
      • If the ‘color[nbr]’ is equal to ‘color[node]’, return false, since this is not possible, as discussed above.
      • Else if the ‘color[nbr]’ is -1, which means it is unassigned, assign it ‘c’.
    • Flip the color after traversing all the ‘nbr’ of ‘node’.
  • If we exit the loop, return true, since all nodes have been assigned colors and no 2 adjacent nodes have the same color.
Time Complexity

O(N ^ 2), where ‘N’ is the number of nodes.

 

As we have to color all the nodes present, and for each node, we have to traverse its neighbors. In the worst cases, there can be at most ‘N’ neighbors. Hence, the overall time complexity is O(N ^ 2).

Space Complexity

O(N), where ‘N’ is the number of nodes.


 

Since we are using an array to store the color of each node and a queue to do BFS, the overall space complexity will be O(N).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Check Bipartite Graph
All tags
Sort by
Search icon

Interview problems

JAVA | BFS

import java.util.*;

public class Solution {

    static class Pair{
        int vt;
        int level;

        Pair(int vt, int level){
            this.vt = vt;
            this.level = level;
        }
    }
    public static boolean isGraphBirpatite(ArrayList<ArrayList<Integer>> edges) {

        int n = edges.size();
        int m = edges.get(0).size();
        ArrayList<Integer>[] graph = new ArrayList[n];

        for(int i= 0; i < n; i++){
            graph[i] = new ArrayList<>();
        }

        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(edges.get(i).get(j) == 1){
                    graph[i].add(j);
                    graph[j].add(i);
                }
            }
        }

        int[] visited = new int[n];
        Arrays.fill(visited, -1);

        for(int i = 0; i < n; i++){
            if(visited[i] == -1){
                if(bfs(graph, visited, i) == false){
                    return false;
                }
            }
        }

        return true;
    }

    public static boolean bfs(ArrayList<Integer>[] graph, int[] visited, int src){

        Queue<Pair> q = new ArrayDeque<>();
        q.add(new Pair(src, 0));

        while(q.size() > 0){
            Pair rem = q.poll();
            
            if(visited[rem.vt] != -1){
                if(rem.level != visited[rem.vt]){
                    return false;
                }
            }else{
                visited[rem.vt] = rem.level;
            }

            for(Integer nbr: graph[rem.vt]){
                if(visited[nbr] == -1){
                    q.add(new Pair(nbr, rem.level+1));
                }
            }
        }

        return true;
    }

}
3 views
0 replies
0 upvotes

Interview problems

Bipartite Graph using BFS Approach #Adjacency List (Coder Army)

#include<bits/stdc++.h>

bool Bipartite(int vertex, vector<int>adj[], vector<int> &color){

    queue<int> q;

    q.push(vertex);

    while(!q.empty()){

        int node = q.front();

        q.pop();

        for(int i=0; i<adj[node].size(); i++){

            if(color[adj[node][i]] == -1){

                color[adj[node][i]] = (color[node] + 1 ) % 2;

                q.push(adj[node][i]);

            }

            else{

                if(color[adj[node][i]] == color[node]){

                    return false;

                }

            }

        }

    }

    return true;

}

bool isGraphBirpatite(vector<vector<int>> &edges) {

    int n = edges.size();

    vector<int> adj[n];

    int u, v;

    for(int i=0; i<n; i++){

        for(int j=0; j<n; j++){

            if(edges[i][j] == 1){

                u = i, v = j;

                adj[u].push_back(v);

                adj[v].push_back(u);

            }

        }

    }

 

    vector<int> color(n, -1);

    for(int i=0; i<n; i++){

        if(color[i] == -1){

            color[i] = 0;

            if(!Bipartite(i, adj, color)){

                return false;

            }

        }

    }

    return true;

}

89 views
0 replies
0 upvotes

Interview problems

Striver Solution || C++

#include<bits/stdc++.h>

using namespace std;

 

bool dfs(int node, int col, int color[], vector<vector<int>> &adj) {

color[node] = col;

 

// traverse adjacent nodes

for(auto it : adj[node]) {

// if uncoloured

if(color[it] == -1) {

if(dfs(it, !col, color, adj) == false) return false;

}

// if previously coloured and have the same colour

else if(color[it] == col) {

return false;

}

}

 

return true;

}

 

bool isGraphBirpatite(vector<vector<int>> &edges) {

// Write your code here.

int n = edges.size();

int m = edges[0].size();

//Queue for BFS

queue <int> q;

//Array to mark the color of the nodes

vector<int> vis(n,-1);

 

//Creating adjacency list from the matrix

vector<vector<int>> adj(n);

for(int i=0;i<n;i++){

for(int j=0;j<m;j++){

if(edges[i][j]==1){

adj[i].push_back(j);

adj[j].push_back(i);

}

}

}

int color[n];

for(int i = 0;i<n;i++) color[i] = -1;

 

// for connected components

for(int i = 0;i<n;i++) {

if(color[i] == -1) {

if(dfs(i, 0, color, adj) == false)

return false;

}

}

return true;

 

}

64 views
0 replies
0 upvotes

Interview problems

easy c++ code || dfs approch || upvote

bool solve(vector<vector<int>>&adj,vector<int>&colour,int col,int node)

{

    colour[node]=col;

    for(auto child:adj[node])

    {

        if(colour[child]==-1)

        {

            if(!solve(adj,colour,!col,child))

            {

                return false;

            }

        }

        else if(colour[child]==colour[node])

        {

            return false;

        }

    }

    return true;

}

bool isGraphBirpatite(vector<vector<int>> &edges) {

    // Write your code here.

    vector<vector<int>>adj(edges.size());

    vector<int>colour(edges.size(),-1);

    for(int i=0; i<edges.size(); ++i)

    {

        for(int j=0; j<edges[i].size(); ++j)

        {

            if(edges[i][j]==1 && i!=j)

            {

                adj[i].push_back(j);

                adj[j].push_back(i);

            }

        }

    }

    for(int i=0; i<edges.size(); ++i)

    {

        if(colour[i]==-1)

        {

            //not a dfs

            if(!solve(adj,colour,0,i))

            {

                return false;

            }

        }

    }

    return true;

}

70 views
0 replies
1 upvote

Interview problems

eZ solution C++ BFS using adjacency list | Explained

#include <bits/stdc++.h>


bool isGraphBirpatite(vector<vector<int>> &edges) {
	// Write your code here.
	// Variable for row and column
	int n = edges.size();
	int m = edges[0].size(); 
	//Queue for BFS
	queue <int> q;
	//Array to mark the color of the nodes
	vector<int> vis(n,-1);


	//Creating adjacency list from the matrix
	vector<vector<int>> adj(n);
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			if(edges[i][j]==1){
				adj[i].push_back(j);
				adj[j].push_back(i);
			}
		}
	}

	//Initial source is 0 so pushing it and marking its color as 0
	q.push(0);
	vis[0]=0;

	//BFS Traversal starts
	while(!q.empty()){
		int u = q.front();
		q.pop();

		//Traversing each node's adjacency list
		for(auto x:adj[u]){
			//If it is not colored then coloring it with the opposite color of the actual node
			if(vis[x]==-1){
				vis[x]=!vis[u];
				//Then pushing it in the queue for later traversal of that node
				q.push(x);
			}
			//If it is already colored as the same color of the actual node that means it might have been colored using some other path and therefore it can never be bipartite
			else if(vis[x]==vis[u]){
				return false;
			}
		}
	}
	//If after the loop the return false doesnt execute that means its a bipartite
	return true;
}
245 views
0 replies
0 upvotes

Interview problems

Easy solution C++ || BFS || without Adjacency List

#include<bits/stdc++.h>

bool check(int start,vector<vector<int>> &edges, vector<int>& vis){
    vis[start] = 0;
    queue<int> q;
    q.push(start); 

    while(!q.empty()){
        int node = q.front();
        q.pop();
 
        for(int i=node+1;i<edges.size();i++){
            if(edges[node][i]==1 && vis[i]==-1){
                vis[i] = !vis[node];
                q.push(i);
            }else if(edges[node][i]==1 && vis[i]==vis[node]){
                return false;
            }
        }
    }

    return true;
}

 

bool isGraphBirpatite(vector<vector<int>> &edges) {
    // Write your code here.

    int n = edges.size();
    vector<int> vis(n , -1); 

    for(int i=0;i<n;i++){
        if(vis[i]==-1){
            if(check(i, edges, vis)==false) return false;
        }
    }

    return true;
}
121 views
0 replies
1 upvote

Interview problems

In Python(3.5) and Python(3.10) I am getting this error. Please fix it.

Traceback (most recent call last): 
File runner.py , line 5, in 
	from solution import isGraphBirpartite ImportError: No module named 'solution'
34 views
1 reply
3 upvotes

Interview problems

SOLUTION USING DFS

bool dfs(int node, int col, int color[], vector<int>adj[]){
	color[node]=col;
	for(auto it : adj[node]){
		if(color[it]==-1){
			if(dfs(it, !col, color, adj)==false) return false;
		}
		else if(color[it]==col){
			return false;
		}
	}
	return true;
}

bool isGraphBirpatite(vector<vector<int>> &edges) {
	// Write your code here.

	//convert adjacency matrix to adjcency list

	int V= edges.size();
	vector<int> adj[V];

	for(int i=0;i<V;i++){
		for(int j=0;j<V;j++){
			if(edges[i][j]==1 && i!=j){
				adj[i].push_back(j);
				adj[j].push_back(i);
			}
		}
	}

	int color[V]; 
	for(int i=0;i<V;i++) color[i]=-1; 

	for(int i=0;i<V;i++){
		if(color[i] == -1){
			if(dfs(i, 0, color, adj)== false) return false;
		}
	}
	return true;
}
445 views
0 replies
1 upvote

Interview problems

Traceback (most recent call last): File runner.py , line 5, in from solution import isGraphBirpartite ImportError: No module named 'solution'

Getting this error on python runtime. Any updates???

52 views
1 reply
3 upvotes

Interview problems

C++ EASY CLEAN CODE (USING BFS)

#include <bits/stdc++.h>
bool check(int node, vector<int>adj[], int color[])
{
	queue<int>q;
	q.push(node);
	color[node] = 0;

	while(!q.empty())
	{
		int n = q.front();
		q.pop();
		for(auto adjnode:adj[n])
		{
			if(color[adjnode] == -1)
			{
				color[adjnode] = !color[n];
				q.push(adjnode);
			}
			else if(color[adjnode] == color[n])
			    return false;
		}
	}
	return true;
}
bool isGraphBirpatite(vector<vector<int>> &edges) {
	int V = edges.size();
	vector<int> adj[V];
	for(int i = 0; i < V; i++)
	{
		for(int j = 0; j < V; j++)
		{
			if(edges[i][j] == 1 && i != j)
			{
				adj[i].push_back(j);
				adj[j].push_back(i);
			}
		}
	}
	int color[V];
	for(int i = 0; i < V; i++)  color[i]=-1;

	for(int i = 0; i < V; i++)
	{
		if(color[i] == -1)
		{
			if(check(i,adj,color) == false)
			    return false;
		}
	}
	return true;
}
470 views
0 replies
1 upvote
Full screen
Console