The Wayback Machine - https://web.archive.org/web/20241217212720/https://www.geeksforgeeks.org/bipartite-graph/
Open In App

Check whether a given graph is Bipartite or not

Last Updated : 26 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an adjacency list representing a graph with V vertices indexed from 0, the task is to determine whether the graph is bipartite or not.

Example:

Input:

Bipartite-Graph

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

Input:

Bipartite-Graph-2

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

Using Breadth-First Search (BFS)

Checking if a graph is bipartite is like trying to color the graph using only two colors, so that no two adjacent vertices have the same color. One approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring problem.

A common and efficient way to solve this is by using Breadth-First Search (BFS). The idea is to traverse the graph level by level and assign colors alternately to the vertices as we proceed.

Step-by-step approach:

  • Start BFS from any uncolored vertex and assign it color 0.
  • For each vertex, color its uncolored neighbors with the opposite color (1 if current is 0, and vice versa)
    • Check if a neighbor already has the same color as the current vertex, return false (graph is not bipartite).
  • If BFS completes without any conflicts, return true (graph is bipartite).

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if the graph is Bipartite using BFS
bool isBipartite(int V, vector<vector<int>> &adj) {

    // Vector to store colors of vertices.
    // Initialize all as -1 (uncolored)
    vector<int> color(V, -1);
    
    // Queue for BFS
    queue<int> q;
    
    // Iterate through all vertices to handle disconnected graphs
    for(int i = 0; i < V; i++) {

        // If the vertex is uncolored, start BFS from it
        if(color[i] == -1) {

            // Assign first color (0) to the starting vertex
            color[i] = 0;
            q.push(i);
            
            // Perform BFS
            while(!q.empty()) {
                int u = q.front();
                q.pop();
                
                // Traverse all adjacent vertices
                for(auto &v : adj[u]) {

                    // If the adjacent vertex is uncolored,
                    // assign alternate color
                    if(color[v] == -1) {
                        color[v] = 1 - color[u];
                        q.push(v);
                    }

                    // If the adjacent vertex has the same color,
                    // graph is not bipartite
                    else if(color[v] == color[u]) {
                        return false;
                    }
                }
            }
        }
    }
    
    // If no conflicts in coloring, graph is bipartite
    return true;
}

int main() {
    // Graph Structure:
    // 0 - 1
    // |   |
    // 3 - 2
    int V = 4;
    vector<vector<int>> adj(V);
    
    // Adding edges (undirected)
    adj[0].push_back(1); adj[1].push_back(0); 
    adj[1].push_back(2); adj[2].push_back(1);  
    adj[2].push_back(3); adj[3].push_back(2);  
    adj[3].push_back(0); adj[0].push_back(3);
    
    if(isBipartite(V, adj))
        cout << "true";
    else
        cout << "false";
    
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX 1000

// Queue structure for BFS
struct Queue {
    int data[MAX];
    int front, rear;
};

void initQueue(struct Queue *q) {
    q->front = q->rear = 0;
}

bool isEmpty(struct Queue *q) {
    return q->front == q->rear;
}

void enqueue(struct Queue *q, int val) {
    q->data[q->rear++] = val;
}

int dequeue(struct Queue *q) {
    return q->data[q->front++];
}

// Function to check if the graph is Bipartite using BFS
bool isBipartite(int V, int adj[V][V]) {
  
    // Array to store colors of vertices, 
    // initialize all as -1 (uncolored)
    int color[V];
    for (int i = 0; i < V; i++) {
        color[i] = -1;
    }

    // Queue for BFS
    struct Queue q;
    initQueue(&q);

    // Iterate through all vertices to handle disconnected graphs
    for (int i = 0; i < V; i++) {
      
        // If the vertex is uncolored, start BFS from it
        if (color[i] == -1) {
          
            // Assign first color (0) to the starting vertex
            color[i] = 0;
            enqueue(&q, i);

            // Perform BFS
            while (!isEmpty(&q)) {
                int u = dequeue(&q);

                // Traverse all adjacent vertices
                for (int v = 0; v < V; v++) {
                    if (adj[u][v] == 1) {
                      
                        // If the adjacent vertex is uncolored,
                        // assign alternate color
                        if (color[v] == -1) {
                            color[v] = 1 - color[u];
                            enqueue(&q, v);
                        }
                        // If the adjacent vertex has the same color,
                        // the graph is not bipartite
                        else if (color[v] == color[u]) {
                            return false;
                        }
                    }
                }
            }
        }
    }

    // If no conflicts in coloring, graph is bipartite
    return true;
}

int main() {
    int V = 4;
    int adj[4][4] = {
        {0, 1, 0, 1},
        {1, 0, 1, 0},
        {0, 1, 0, 1},
        {1, 0, 1, 0}
    };

    if (isBipartite(V, adj))
        printf("true\n");
    else
        printf("false\n");

    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to check if the graph is Bipartite using BFS
    static boolean isBipartite(int V,
                               List<List<Integer> > adj){
        int[] color = new int[V];

        // Initialize all as -1 (uncolored)
        Arrays.fill(color, -1);

        // Iterate through all vertices to handle
        // disconnected graphs
        for (int i = 0; i < V; i++) {

            // If the vertex is uncolored, start BFS from it
            if (color[i] == -1) {

                // Assign first color (0)
                color[i] = 0;
                Queue<Integer> q = new LinkedList<>();

                // Add starting vertex to the queue
                q.offer(i);

                while (!q.isEmpty()) {
                    int u = q.poll();

                    // Traverse all adjacent vertices
                    for (int v : adj.get(u)) {

                        // If the adjacent vertex is
                        // uncolored, assign alternate color
                        if (color[v] == -1) {
                            color[v] = 1 - color[u];

                            q.offer(v);
                        }

                        // If the adjacent vertex has the
                        // same color, graph is not
                        // bipartite
                        else if (color[v] == color[u]) {
                            return false;
                        }
                    }
                }
            }
        }
        // If no conflicts in coloring, graph is bipartite
        return true;
    }

    public static void main(String[] args){
        // Graph Structure:
        // 0 - 1
        // |   |
        // 3 - 2
        int V = 4;
        List<List<Integer> > adj = new ArrayList<>();
        for (int i = 0; i < V; i++)
            adj.add(new ArrayList<>());

        // Adding edges (undirected)
        adj.get(0).add(1); adj.get(1).add(0);
        adj.get(1).add(2); adj.get(2).add(1);
        adj.get(2).add(3); adj.get(3).add(2);
        adj.get(3).add(0); adj.get(0).add(3);

        if (isBipartite(V, adj))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
from collections import deque

# Function to check if the graph is Bipartite using BFS
def isBipartite(V, adj):

    # Initialize all as -1 (uncolored)
    color = [-1] * V

    for i in range(V):

        # If the vertex is uncolored, start BFS from it
        if color[i] == -1:

            # Assign first color (0)
            color[i] = 0
            q = deque([i])

            while q:
                u = q.popleft()
                
                # Traverse all adjacent vertices
                for v in adj[u]:

                    # If the adjacent vertex is uncolored,
                    # assign alternate color
                    if color[v] == -1:
                        color[v] = 1 - color[u]
                        q.append(v)

                    # If the adjacent vertex has the same color,
                    # graph is not bipartite
                    elif color[v] == color[u]:
                        return False  

    # If no conflicts in coloring, graph is bipartite
    return True 

if __name__ == "__main__":
    # Graph Structure:
    # 0 - 1
    # |   |
    # 3 - 2
    V = 4
    adj = [[] for _ in range(V)]

    # Adding edges (undirected)
    adj[0].append(1)
    adj[1].append(0)
    adj[1].append(2)
    adj[2].append(1)
    adj[2].append(3)
    adj[3].append(2)
    adj[3].append(0)
    adj[0].append(3)

    if isBipartite(V, adj):
        print("true")
    else:
        print("false")
C#
using System;
using System.Collections.Generic;

class GfG {
  
    // Function to check if the graph is Bipartite using BFS
    public static bool IsBipartite(int V,
                                   List<List<int> > adj){
        int[] color = new int[V];

        // Initialize all as -1 (uncolored)
        Array.Fill(color, -1);

        // Iterate through all vertices to handle
        // disconnected graphs
        for (int i = 0; i < V; i++) {

            // If the vertex is uncolored, start BFS from it
            if (color[i] == -1) {

                // Assign first color (0)
                color[i] = 0;
                Queue<int> q = new Queue<int>();
                q.Enqueue(i);

                // Perform BFS
                while (q.Count > 0) {
                    int u = q.Dequeue();

                    // Traverse all adjacent vertices
                    foreach(int v in adj[u]){

                        // If the adjacent vertex is
                        // uncolored, assign alternate color
                        if (color[v] == -1) {
                            color[v] = 1 - color[u];
                            q.Enqueue(v);
                        }
                      
                        // If the adjacent vertex has the
                        // same color, graph is not
                        // bipartite
                        else if (color[v] == color[u]) {
                            return false;
                        }
                    }
                }
            }
        }
      
        // If no conflicts in coloring, graph is bipartite
        return true;
    }

    static void Main(){
        // Graph Structure:
        // 0 - 1
        // |   |
        // 3 - 2
        int V = 4;
        List<List<int> > adj = new List<List<int> >();
        for (int i = 0; i < V; i++)
            adj.Add(new List<int>());

        // Adding edges (undirected)
        adj[0].Add(1);
        adj[1].Add(0);
        adj[1].Add(2);
        adj[2].Add(1);
        adj[2].Add(3);
        adj[3].Add(2);
        adj[3].Add(0);
        adj[0].Add(3);

        if (IsBipartite(V, adj))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
function isBipartite(V, adj){

    // Initialize all as -1 (uncolored)
    const color = Array(V).fill(-1);

    // Iterate through all vertices to handle disconnected
    // graphs
    for (let i = 0; i < V; i++) {

        // If the vertex is uncolored, start BFS from it
        if (color[i] === -1) {

            // Assign first color (0)
            color[i] = 0;
            const queue = [ i ];

            // Perform BFS
            while (queue.length > 0) {
                const u = queue.shift();

                // Traverse all adjacent vertices
                for (let v of adj[u]) {

                    // If the adjacent vertex is uncolored,
                    // assign alternate color
                    if (color[v] === -1) {
                        color[v] = 1 - color[u];
                        queue.push(v); // Push to queue
                    }

                    // If the adjacent vertex has the same
                    // color, graph is not bipartite
                    else if (color[v] === color[u]) {
                        return false;
                    }
                }
            }
        }
    }
    
    // If no conflicts in coloring, graph is bipartite
    return true;
}

// Driver Code
const V = 4;
const adj = Array.from({length : V}, () => []);

// Adding edges (undirected)
adj[0].push(1);
adj[1].push(0);
adj[1].push(2);
adj[2].push(1);
adj[2].push(3);
adj[3].push(2);
adj[3].push(0);
adj[0].push(3);

console.log(isBipartite(V, adj));

Output
true

Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges. This is because BFS explores each vertex and edge exactly once.
Auxiliary Space: O(V), The queue used in BFS, which can hold up to V vertices and The color array (or map), which stores the color for each vertex

Using Depth-First Search (DFS)

We can also check if a graph is bipartite using Depth-First Search (DFS). We need to color the graph with two colors such that no two adjacent vertices share the same color. We start from any uncolored vertex, assigning it a color (e.g., color 0). As we explore each vertex, we recursively color its uncolored neighbors with the another color. If we ever find a neighbor that shares the same color as the current vertex, we can simply conclude that the graph is not bipartite. If there is no conflict found after the traversal then the given graph is bipartite.

For implementation of DFS approach please refer to this article “Check if a given graph is Bipartite using DFS“.

Related Article:



Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg