×

Bipartite Graph

A graph is said to be bipartite if and only if we can divide all the vertices of a graph into two sets such that these sets are mutually exclusive and exhaustive, and all the edges of the graph are cross sets, and not a single edge should be in the same set.

It means let's suppose we have N vertices in a graph, and we divide them into two sets, S1 and S2 then.

 and  and every edge should be from S1 to S2.

For example: 

Bipartite Graph

In the above graph, we can see that we divide the vertices into two sets, S1 and S2. They are mutually exclusive and exhaustive. Also, there is no edge belonging to the same set. All the edges are cross-sets. So this graph is a bipartite graph.

Another simplest definition of a bipartite graph is that if we can color the graph with only two colors and adjacent vertices should not have the same color, then it is bipartite, else it is not bipartite.

For example:

Bipartite Graph

In the above examples, both graph 1 and graph 2 are both bipartite. Graph 1 and graph 2 both can color with just 2 colors and no adjacent vertices have the same color.

Graph 1 is acyclic, and Graph 2 has a cycle.

But we can see the cycle length in graph 2 is 4, which is even.

So, we can conclude that if a graph is acyclic or it has an even length cycle, then it is bipartite else, it is not bipartite.

For example:

Bipartite Graph

In the graph, we will see that at vertex 5, we can’t use any color because it violates our condition. The above graph is not bipartite. We can see that there are two cycles in the above graph. The first cycle has a length of 5 and the second cycle has a length of 4. So length 5 cycle has the problem so that we can say, “if a graph has an odd length cycle, it will definitely not be bipartite else, it will be bipartite.

For code implementation, we will use BFS/DFS traversal. From the source node when we are starting the traversal, then we will color it either 0 or 1. After that see for its adjacent neighbors, if its adjacent is unvisited, then make their color different and call DFS for them. If adjacent nodes have the same color, return false otherwise return true.

DFS Code in JAVA

import java.util.*;
public class Main{
    public static void main(String[] args){
         int n = 5;
        ArrayList < ArrayList < Integer >> graph = new ArrayList < ArrayList < Integer >> ();


        for (int i = 0; i < n+1; i++)
            graph.add(new ArrayList < Integer > ());


        graph.get(1).add(2);
        graph.get(2).add(1);


        graph.get(2).add(3);
        graph.get(3).add(2);


        graph.get(3).add(4);
        graph.get(4).add(3);


        graph.get(4).add(5);
        graph.get(5).add(4);
        
        graph.get(5).add(1);
        graph.get(1).add(5);


        System.out.println(isBipartite(graph,n));
    }
    
    public static boolean isBipartite(ArrayList<ArrayList<Integer>> graph,int n){
        
        int[] color=new int[n+1];
        Arrays.fill(color,-1);
        for(int i=1;i<=n;i++){
            if(color[i]==-1){
                color[i]=0;
                if(dfs(graph,color,i)==false)
                return false;
            }
        }
        return true;
    }
    public static boolean dfs(ArrayList<ArrayList<Integer>> graph,int[] color,int node){
        
        for(int nbr: graph.get(node)){
            if(color[nbr]==-1){
                color[nbr]=1-color[node];
                if(dfs(graph,color,nbr)==false) 
                  return false;
            }else if(color[nbr]==color[node]){
                return false;
            }
        }
        return true;
    }
}

Time complexity

As we are traversing all the nodes, suppose the total number of nodes is N and the edge is E.

So time complexity would be: O(N+E).

Space complexity

O(N) for color array, O(N) for recursive stack space, and O(2*E) for 2d array list of graphs.

So if we ignore the space for the graph, then space complexity would be : O(N)+O(N) or O(N). We can also use BFS traversal of graphs.

Java Code for BFS

import java.util.*;
public class Main{
    public static void main(String[] args){
         int n = 5;
        ArrayList < ArrayList < Integer >> graph = new ArrayList < ArrayList < Integer >> ();


        for (int i = 0; i < n+1; i++)
            graph.add(new ArrayList < Integer > ());


        graph.get(1).add(2);
        graph.get(2).add(1);


        graph.get(2).add(3);
        graph.get(3).add(2);


        graph.get(3).add(4);
        graph.get(4).add(3);


        graph.get(4).add(5);
        graph.get(5).add(4);
        
        graph.get(5).add(1);
        graph.get(1).add(5);


        System.out.println(isBipartite(graph,n));
    }
    
    public static boolean isBipartite(ArrayList<ArrayList<Integer>> graph,int n){
        
        int[] color=new int[n+1];
        Arrays.fill(color,-1);
        for(int i=1;i<=n;i++){
            if(color[i]==-1){
                if(bfs(graph,color,i)==false)
                return false;
            }
        }
        return true;
    }
    public static boolean bfs(ArrayList<ArrayList<Integer>> graph,int[] color,int node){
        
       Queue<Integer> q = new ArrayDeque<>();
       q.add(node);
       color[node]=0;
       while(q.size()>0){
           int top=q.poll();
           for(int nbr:graph.get(top)){
               if(color[nbr]==-1){
                   color[nbr]=1-color[top];
                   q.add(nbr);
               }else if(color[nbr]==color[top])
               {
                   return false;
               }
           }
       }
       return true;
    }
}

Time complexity

Here, we are traversing all over the graph so that it would be O(N+E).

Space complexity

O(N) for queue using and  O(N) for color array. If we ignore the space required to store the graph, then space complexity would be: O(N)


Related Topics

Computer Organization and Architecture Data Formats

Data Formats In the digital world, everything is based on digits. In every method, the calculation is processed on the digits, and most importantly, the computer only understands the binary language...

6 minutes read.

Use Case Diagram for the online bank system

What is a Use Case Diagram? A tool is called a Use Case Diagram which is used to create, present, and comprehend the functional requirements for a system. The Use Case...

3 minutes read.

Microprocessor classification

Introduction: Microprocessor is known as the computer processor. The IC or integrated Circuit makes the microprocessor. that is the brain of the computer machine. The microprocessor is known as the...

6 minutes read.

Convert a number from base 2 to base 6

Base 2 Base 2 is the format where you can represent any number with just two values which are 0 and 1. With the help of 0s and 1s, we can...

4 minutes read.

Instruction Pipelining and Pipeline Hazards

Instruction Pipelining and Pipeline Hazards To apply pipeline, the prerequisite is to perform the same processing over multiple inputs, then pipelining is important. So instruction execution is the best example for...

10 minutes read.

Local Broadcast Address and loopback address

In computer networking, if you send the data from one source to another source or group of sources in the form of packets, then this is called casting. We can categorize...

3 minutes read.

Machine Instructions

What is a Digital Computer? A computer that takes input in a binary form and produces output in binary form. The question arises of what kind of input the computer takes...

4 minutes read.

Fixed and Floating-Point Number

Fixed and Floating-Point Number: In digital technology, data is stored in memory registers with binary bits 0’s and 1’s because the computer only understands binary language. When we enter data...

6 minutes read.

8255 Microprocessor Operating Modes

8255 microprocessor was invented by intel in the year 1980s. 8255 microprocessor is a general-purpose microprocessor that can be programmed. 8255 is mostly used as an interface between devices like...

3 minutes read.

8085 instructions set

Introduction: In the computer, the user sends the data. The computer can use data and it also process the data. After the processing, send the result to the user. The specific...

10 minutes read.

Flag Register of 8086 Microprocessor

In this article, we are going to study about the one of the registers named flag registers of 8086 microprocessor. We are also going to know where and how to...

3 minutes read.

8086 Microprocessor Pin Configurations

8086 microprocessor is invented and developed by Intel in 1976. The 8086 Microprocessor is an enhanced version of the 8085 Microprocessor. There are 20 address lines and 16 data lines...

6 minutes read.

8085 Arithmetic Instructions

Arithmetic instructions are a type of instruction in a computer's instruction set that perform arithmetic operations on data. These operations can include addition, subtraction, multiplication, and division. Arithmetic instructions can...

4 minutes read.

COA: Interrupt and its types

Introduction: In general terms, the word interrupt means to stop the progress of ongoing work in between or to break the continuation of the work. In early digital computing, the...

5 minutes read.

Data Path, ALU and Control Unit

Data Path, ALU(Arithmetic Logic Unit) and Control Unit What is the Data path? Suppose any data processing operation should be performed in the CPU like transferring the content of register from one...

5 minutes read.

Basic Terminologies Related to COA

Some Basic Terminologies Related to COA Computer organization and architecture is the detailed study of the internal components of the computer with their functionality. It describes how components arranged together and...

7 minutes read.

Addressing Modes

Introduction: Addressing Modes An instruction consists of two parts opcode and operands. Opcode tells the operation going to perform, and operand information is the address of the operand. The CPU interprets...

8 minutes read.

Ethernet Frame Format

What is Ethernet? As we know in computer networking, LAN (Local Area Network) is used to connect devices in limited geographical areas like schools or a building.LAN uses different topologies (arrangement...

3 minutes read.

Pipelining: Computer Organization and Architecture

Introduction to Pipelining Before learning pipeline, we have to understand about the Parallel processing. Parallel processing is the processing of data simultaneously. There are three techniques of parallel processing. Types of Processing: Vector ProcessingArray...

7 minutes read.

Assembly Language Register

Assembly Language Register Assembly language was introduced during the late 1940s in the second generation. It is a low-level language that helps in communication between the user and the computer. It...

6 minutes read.