Check whether a given graph is Bipartite or not

Last Updated : 1 Dec, 2026

Given an undirected graph represented by an adjacency list adj[][], check whether the graph is bipartite or not.

A bipartite graph is a graph whose vertices can be colored using two colors such that no two adjacent vertices have the same color. Equivalently, the vertices can be divided into two disjoint sets such that:

  • Every edge connects a vertex from one set to a vertex in the other set.
  • No edge connects two vertices within the same set.

Examples:

Input: adj[][] = [[1], [0, 2], [1]]

10

Output: true
Explanation: The vertices can be colored using two colors such that every pair of adjacent vertices has different colors.

Input: adj[][] = [[2, 3], [2], [0, 1, 3], [0, 2]]

11

Output: false
Explanation: The vertices form a triangle, so it is not possible to color them using two colors without two adjacent vertices having the same color.

Try It Yourself
redirect icon

[Naive Approach] Backtracking - O(2^V × (V + E)) Time and O(V) Space

The idea is to recursively assign one of the two colors to every vertex. Before assigning a color, check whether any adjacent vertex already has the same color. If no valid coloring is possible after trying both colors, the graph is not bipartite.

Working of Approach:

  • Create an adjacency list from the given edges.
  • Recursively assign either color 0 or 1 to every uncolored vertex.
  • Before assigning a color, ensure that none of its adjacent vertices has the same color.
  • If a color leads to a conflict, backtrack and try the other color.
  • If all vertices are colored successfully, return true; otherwise, return false.
C++
#include <iostream>
#include <vector>
using namespace std;

bool isSafe(int node, int clr, vector<int> &color, vector<vector<int>> &adj)
{
    // Check all adjacent vertices.
    for (int neigh : adj[node])
    {
        if (color[neigh] == clr)
            return false;
    }

    return true;
}

bool solve(int node, int V, vector<int> &color, vector<vector<int>> &adj)
{
    // All vertices are colored.
    if (node == V)
        return true;

    // Skip already colored vertices.
    if (color[node] != -1)
        return solve(node + 1, V, color, adj);

    // Try both colors.
    for (int clr = 0; clr <= 1; clr++)
    {
        if (isSafe(node, clr, color, adj))
        {
            // Assign color.
            color[node] = clr;

            // Recur for next vertex.
            if (solve(node + 1, V, color, adj))
                return true;

            // Backtrack.
            color[node] = -1;
        }
    }

    return false;
}

bool isBipartite(vector<vector<int>> &adj)
{
    int V = adj.size();

    // -1 means vertex is uncolored.
    vector<int> color(V, -1);

    return solve(0, V, color, adj);
}

int main()
{
    vector<vector<int>> adj = {{1}, {0, 2}, {1}};

    if (isBipartite(adj))
        cout << "true";
    else
        cout << "false";

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

class GFG {
    static boolean isSafe(int node, int clr, int[] color,
           ArrayList<ArrayList<Integer> > adj) {
               
        // Check all adjacent vertices.
        for (int neigh : adj.get(node)) {
            if (color[neigh] == clr)
                return false;
        }

        return true;
    }

    static boolean solve(int node, int V, int[] color, ArrayList<ArrayList<Integer> > adj) {
        // All vertices are colored.
        if (node == V)
            return true;

        // Skip already colored vertices.
        if (color[node] != -1)
            return solve(node + 1, V, color, adj);

        // Try both colors.
        for (int clr = 0; clr <= 1; clr++) {
            if (isSafe(node, clr, color, adj)) {
                
                // Assign color.
                color[node] = clr;

                // Recur for next vertex.
                if (solve(node + 1, V, color, adj))
                    return true;

                // Backtrack.
                color[node] = -1;
            }
        }

        return false;
    }

    static boolean isBipartite(ArrayList<ArrayList<Integer> > adj) {
        int V = adj.size();

        // -1 means vertex is uncolored.
        int[] color = new int[V];
        Arrays.fill(color, -1);

        return solve(0, V, color, adj);
    }

    public static void main(String[] args)
    {
        ArrayList<ArrayList<Integer> > adj
            = new ArrayList<>();
        adj.add(new ArrayList<>(Arrays.asList(1)));
        adj.add(new ArrayList<>(Arrays.asList(0, 2)));
        adj.add(new ArrayList<>(Arrays.asList(1)));

        System.out.println(isBipartite(adj) ? "true"
                                            : "false");
    }
}
Python
def isSafe(node, clr, color, adj):
    # Check all adjacent vertices.
    for neigh in adj[node]:
        if color[neigh] == clr:
            return False

    return True


def solve(node, V, color, adj):
    # All vertices are colored.
    if node == V:
        return True

    # Skip already colored vertices.
    if color[node] != -1:
        return solve(node + 1, V, color, adj)

    # Try both colors.
    for clr in range(2):
        if isSafe(node, clr, color, adj):
            
            # Assign color.
            color[node] = clr

            # Recur for next vertex.
            if solve(node + 1, V, color, adj):
                return True

            # Backtrack.
            color[node] = -1

    return False


def isBipartite(adj):
    V = len(adj)

    # -1 means vertex is uncolored.
    color = [-1] * V

    return solve(0, V, color, adj)


# Driver Code
if __name__ == "__main__":
    adj = [[1], [0, 2], [1]]

    print(str(isBipartite(adj)).lower())
C#
using System;
using System.Collections.Generic;

class GFG {
    static bool isSafe(int node, int clr, int[] color, List<List<int>> adj) {
        // Check all adjacent vertices.
        foreach(int neigh in adj[node])
        {
            if (color[neigh] == clr)
                return false;
        }

        return true;
    }

    static bool solve(int node, int V, int[] color, List<List<int> > adj) {
        // All vertices are colored.
        if (node == V)
            return true;

        // Skip already colored vertices.
        if (color[node] != -1)
            return solve(node + 1, V, color, adj);

        // Try both colors.
        for (int clr = 0; clr <= 1; clr++) {
            if (isSafe(node, clr, color, adj)) {
                // Assign color.
                color[node] = clr;

                // Recur for next vertex.
                if (solve(node + 1, V, color, adj))
                    return true;

                // Backtrack.
                color[node] = -1;
            }
        }

        return false;
    }

    // Function to check if graph is bipartite.
    static bool isBipartite(List<List<int> > adj) {
        int V = adj.Count;

        // -1 means vertex is uncolored.
        int[] color = new int[V];
        Array.Fill(color, -1);

        return solve(0, V, color, adj);
    }

    static void Main() {
        List<List<int>> adj = 
        new List<List<int>>{ new List<int>{ 1 }, new List<int>{ 0, 2 }, new List<int>{ 1 } };

        Console.WriteLine(isBipartite(adj) ? "true"
                                           : "false");
    }
}
JavaScript
function isSafe(node, clr, color, adj)
{
    // Check all adjacent vertices.
    for (let neigh of adj[node]) {
        if (color[neigh] === clr)
            return false;
    }

    return true;
}

function solve(node, V, color, adj)
{
    // All vertices are colored.
    if (node === V)
        return true;

    // Skip already colored vertices.
    if (color[node] !== -1)
        return solve(node + 1, V, color, adj);

    // Try both colors.
    for (let clr = 0; clr <= 1; clr++) {
        if (isSafe(node, clr, color, adj)) {
            // Assign color.
            color[node] = clr;

            // Recur for next vertex.
            if (solve(node + 1, V, color, adj))
                return true;

            // Backtrack.
            color[node] = -1;
        }
    }

    return false;
}

function isBipartite(adj)
{
    let V = adj.length;

    // -1 means vertex is uncolored.
    let color = new Array(V).fill(-1);

    return solve(0, V, color, adj);
}

// Driver Code
let adj = [ [ 1 ], [ 0, 2 ], [ 1 ] ];
console.log(isBipartite(adj));

Output
true

Time Complexity: O(2^V × (V + E)), since each vertex can be assigned one of two colors, and every assignment checks adjacent vertices.
Space Complexity: O(V), The color array and recursion stack require O(V) space.

[Expected Approach] BFS Traversal - O(V + E) Time and O(V) Space

The idea is to perform a BFS traversal and color each vertex with one of two colors. Every adjacent vertex is assigned the opposite color. If two adjacent vertices are found with the same color, the graph is not bipartite.

Working of Approach:

  • Create an adjacency list from the given edges.
  • Start BFS from every unvisited vertex to handle disconnected graphs.
  • Assign the starting vertex color 0 and color every neighbor with the opposite color.
  • If an already colored neighbor has the same color as the current vertex, return false.
  • If BFS finishes without any conflict, return true.

Let us understand with an example:
Input: adj[][] = [[1], [0, 2], [1]]

10
  • Initialize the color array as [-1, -1, -1] and start BFS from vertex 0.
  • Assign color 0 to vertex 0 and push it into the queue.
  • Visit vertex 1, assign it the opposite color 1, and push it into the queue.
  • Visit vertex 2 from vertex 1 and assign it color 0.
  • Every adjacent pair of vertices has different colors, so no conflict is found.
  • Therefore, the graph is bipartite, and the answer is true.
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// Function to check if the graph is bipartite or not
bool isBipartite(vector<vector<int>> &adj)
{
    int V = adj.size();

    // 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()
{
    vector<vector<int>> adj = {{1}, {0, 2}, {1}};

    if (isBipartite(adj))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java
import java.util.Queue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;

class GFG {

    // Function to check if the graph is bipartite or not
    static boolean isBipartite(ArrayList<ArrayList<Integer>> adj) {
        int V = adj.size();

        // Vector to store colors of vertices.
        // Initialize all as -1 (uncolored)
        int[] color = new int[V];
        Arrays.fill(color, -1);

        // Queue for BFS
        Queue<Integer> q = new LinkedList<>();

        // 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.add(i);

                // Perform BFS
                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.add(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) {
        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
        adj.add(new ArrayList<>(Arrays.asList(1)));
        adj.add(new ArrayList<>(Arrays.asList(0, 2)));
        adj.add(new ArrayList<>(Arrays.asList(1)));

        System.out.println(isBipartite(adj));
    }
}
Python
from collections import deque

# Function to check if the graph is bipartite or not
def isBipartite(adj):
    V = len(adj)

    # List to store colors of vertices.
    # Initialize all as -1 (uncolored)
    color = [-1] * V

    # Queue for BFS
    q = deque()

    # Iterate through all vertices to handle disconnected graphs
    for i in range(V):
        # 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.append(i)

            # Perform BFS
            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

# Driver Code
if __name__ == '__main__':
    adj = [[1], [0, 2], [1]]

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

public class GFG {
    public static bool isBipartite(List<List<int> > adj)
    {
        int V = adj.Count;

        // List to store colors of vertices.
        // Initialize all as -1 (uncolored)
        int[] color = new int[V];
        for (int i = 0; i < V; i++) {
            color[i] = -1;
        }

        // Queue for BFS
        Queue<int> q = new Queue<int>();

        // 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.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;
    }

    public static void Main()
    {
        List<List<int> > adj
            = new List<List<int> >{ new List<int>{ 1 },
                                    new List<int>{ 0, 2 },
                                    new List<int>{ 1 } };

        if (isBipartite(adj))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// Function to check if the graph is bipartite or not
function isBipartite(adj)
{
    let V = adj.length;

    // Vector to store colors of vertices.
    // Initialize all as -1 (uncolored)
    let color = new Array(V).fill(-1);

    // Queue for BFS
    let q = [];

    // 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) to the starting vertex
            color[i] = 0;
            q.push(i);

            // Perform BFS
            while (q.length > 0) {
                let u = q.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];
                        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;
}

// Driver code
let adj = [ [ 1 ], [ 0, 2 ], [ 1 ] ];
console.log(isBipartite(adj));

Output
true

[Alternate Approach] DFS Traversal - O(V + E) Time and O(V) Space

The idea is to perform a DFS traversal and color each vertex with one of two colors. During DFS, every adjacent vertex is assigned the opposite color. If two adjacent vertices receive the same color, the graph is not bipartite.

Working of Approach:

  • Create an adjacency list from the given edges.
  • Start DFS from every unvisited vertex.
  • Assign alternate colors while visiting adjacent vertices.
  • If an adjacent vertex already has the same color, return false.
  • If all components are colored successfully, return true.
C++
#include <iostream>
#include <vector>
using namespace std;

// DFS function to color vertices.
bool dfs(int node, int clr, vector<int> &color, vector<vector<int>> &adj)
{
    // Assign color to current vertex.
    color[node] = clr;

    // Visit all adjacent vertices.
    for (int neigh : adj[node])
    {
        // If the adjacent vertex is uncolored,
        // assign alternate color.
        if (color[neigh] == -1)
        {
            if (!dfs(neigh, 1 - clr, color, adj))
                return false;
        }

        // If the adjacent vertex has the same color,
        // graph is not bipartite.
        else if (color[neigh] == clr)
        {
            return false;
        }
    }

    return true;
}

bool isBipartite(vector<vector<int>> &adj)
{
    int V = adj.size();

    // -1 means vertex is uncolored.
    vector<int> color(V, -1);

    // Traverse every connected component.
    for (int i = 0; i < V; i++)
    {
        if (color[i] == -1)
        {
            if (!dfs(i, 0, color, adj))
                return false;
        }
    }

    return true;
}

int main()
{
    vector<vector<int>> adj = {{1}, {0, 2}, {1}};

    if (isBipartite(adj))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

class GFG {
    static boolean dfs(int node, int clr, int[] color, ArrayList<ArrayList<Integer> > adj)
    {
        // Assign color to current vertex.
        color[node] = clr;

        // Visit all adjacent vertices.
        for (int neigh : adj.get(node)) {

            // If the adjacent vertex is uncolored,
            // assign alternate color.
            if (color[neigh] == -1) {
                if (!dfs(neigh, 1 - clr, color, adj))
                    return false;
            }

            // If the adjacent vertex has the same color,
            // graph is not bipartite.
            else if (color[neigh] == clr) {
                return false;
            }
        }

        return true;
    }

    static boolean isBipartite(ArrayList<ArrayList<Integer> > adj)
    {
        int V = adj.size();

        // -1 means vertex is uncolored.
        int[] color = new int[V];
        Arrays.fill(color, -1);

        // Traverse every connected component.
        for (int i = 0; i < V; i++) {
            if (color[i] == -1) {
                if (!dfs(i, 0, color, adj))
                    return false;
            }
        }

        return true;
    }

    public static void main(String[] args)
    {
        ArrayList<ArrayList<Integer> > adj
            = new ArrayList<>();
        adj.add(new ArrayList<>(Arrays.asList(1)));
        adj.add(new ArrayList<>(Arrays.asList(0, 2)));
        adj.add(new ArrayList<>(Arrays.asList(1)));

        if (isBipartite(adj))
            System.out.print("true");
        else
            System.out.print("false");
    }
}
Python
# DFS function to color vertices.
def dfs(node, clr, color, adj):

    # Assign color to current vertex.
    color[node] = clr

    # Visit all adjacent vertices.
    for neigh in adj[node]:

        # If the adjacent vertex is uncolored,
        # assign alternate color.
        if color[neigh] == -1:
            if not dfs(neigh, 1 - clr, color, adj):
                return False

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

    return True


def isBipartite(adj):
    V = len(adj)

    # -1 means vertex is uncolored.
    color = [-1] * V

    # Traverse every connected component.
    for i in range(V):
        if color[i] == -1:
            if not dfs(i, 0, color, adj):
                return False

    return True


# Driver Code
if __name__ == "__main__":
    adj = [[1], [0, 2], [1]]

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

class GFG {
    static bool dfs(int node, int clr, int[] color, List<List<int> > adj)
    {
        // Assign color to current vertex.
        color[node] = clr;

        // Visit all adjacent vertices.
        foreach(int neigh in adj[node])
        {
            // If the adjacent vertex is uncolored,
            // assign alternate color.
            if (color[neigh] == -1) {
                if (!dfs(neigh, 1 - clr, color, adj))
                    return false;
            }

            // If the adjacent vertex has the same color,
            // graph is not bipartite.
            else if (color[neigh] == clr) {
                return false;
            }
        }

        return true;
    }

    static bool isBipartite(List<List<int> > adj)
    {
        int V = adj.Count;

        // -1 means vertex is uncolored.
        int[] color = new int[V];
        Array.Fill(color, -1);

        // Traverse every connected component.
        for (int i = 0; i < V; i++) {
            if (color[i] == -1) {
                if (!dfs(i, 0, color, adj))
                    return false;
            }
        }

        return true;
    }

    static void Main()
    {
        List<List<int> > adj
            = new List<List<int> >{ new List<int>{ 1 },
                                    new List<int>{ 0, 2 },
                                    new List<int>{ 1 } };

        if (isBipartite(adj))
            Console.Write("true");
        else
            Console.Write("false");
    }
}
JavaScript
// DFS function to color vertices.
function dfs(node, clr, color, adj)
{
    // Assign color to current vertex.
    color[node] = clr;

    // Visit all adjacent vertices.
    for (let neigh of adj[node]) {

        // If the adjacent vertex is uncolored,
        // assign alternate color.
        if (color[neigh] === -1) {
            if (!dfs(neigh, 1 - clr, color, adj))
                return false;
        }

        // If the adjacent vertex has the same color,
        // graph is not bipartite.
        else if (color[neigh] === clr) {
            return false;
        }
    }

    return true;
}

function isBipartite(adj)
{
    let V = adj.length;

    // -1 means vertex is uncolored.
    let color = new Array(V).fill(-1);

    // Traverse every connected component.
    for (let i = 0; i < V; i++) {
        if (color[i] === -1) {
            if (!dfs(i, 0, color, adj))
                return false;
        }
    }

    return true;
}

// Driver code
let adj = [ [ 1 ], [ 0, 2 ], [ 1 ] ];

if (isBipartite(adj))
    console.log("true");
else
    console.log("false");

Output
true
Comment