×

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

Biconnectivity in a Graph

What is a Graph? A graph is a structure where values are stored at the vertex, and the relation between vertices is denoted by edges. In a graph, if there is only...

4 minutes read.

Control Signals in 8155 Microprocessor

Intel designed the chip 8155 used to interface with I/O devices. Basically, the 8085 microprocessor is directly unable to deal with its peripheral input output devices for reading data or...

3 minutes read.

Control Unit Organization

Control Unit Organization The Control Unit is the unit in the CPU, which controls the various components like input  & output devices, logic unit and memory. The Control Unit is the...

7 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.

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.

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.

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.

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.

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.

Advantages and Disadvantages of Flash Memory

What is Flash Memory? Electrically Erasable Programmable Read-Only Memory (EEPROM) and Erasable Programmable Read-Only Memory (EPROM) are used for flash memory (EEPROM). Although technically the word flash is used in the industry...

3 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.

Interfacing DAC with the 8051 Microcontroller

A wide range of applications calls for microcontrollers, including measuring and controlling physical quantities like temperature, pressure, speed, and distance. In these systems, the microcontroller creates digital output, but the controlling...

2 minutes read.

Addressing mode in 8085 microprocessor

What is a Microprocessor? Microprocessor is a unit which is able to perform arithmetic and logical operations and is built on a single chip. The 8085 microprocessor is built by Intel which...

4 minutes read.

BCD to 7 Segment Decoder

What is BCD? BCD is called Binary Coded Decimal. As you know there are a lot of forms in which we can represent the number like Binary, decimal, hexadecimal, and octal...

3 minutes read.

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...

4 minutes read.

8085 Pin Configuration

Introduction: Intel 8085 is consist 40 pin IC. The pin name of 8085 is A8 – A15; AD0 – AD7; ALE; IO/M; S0, S1; RD; WR; READY; HOLD; HLDA; INTR; INTA;...

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.

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.

Instruction Cycle: Computer Organization and Architecture

What is an effective Address? “Effective address is the address of operand in a computation-type instruction.” Computation type instructions are like ADD, SUB, MOV, OR, AND, etc., which require operand to...

4 minutes read.

Micro-Operations

Micro-Operations If CPU wants to perform any operation, suppose execution of only one instruction or even break it down one particular execution phase (like fetch instruction, write back, decode, operand fetch...

9 minutes read.