Check if a given graph is Bipartite using DFS (original) (raw)

Last Updated : 11 Jul, 2025

Given a graph with **V vertices numbered from **0 to V-1 and a list of **edges, determine whether the graph is **bipartite or not.

**Note: A **bipartite graph is a type of graph where the set of vertices can be divided into **two disjoint sets, say **U and **V, such that **every edge connects a vertex in U to a vertex in V, there are **no edges between vertices within the same set.

**Example:

**Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]]
**Output: false
**Explanation:

Detect-cycle-in-an-undirected-graph-1

The graph is not bipartite because no matter how we try to color the nodes using two colors, there exists a cycle of odd length (like 1–2–0–1), which leads to a situation where two adjacent nodes end up with the same color. This violates the bipartite condition, which requires that no two connected nodes share the same color.

**Input: _V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]]
**Output: true
**Explanation:

Detect-cycle-in-an-undirected-graph-2

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

In the previous post, we have discussed a BFS approach. In this post, we will cover the DFS approach.

**Approach: Using Depth-First Search - O(V+E) Time and O(V) Space

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

**Step-by-step approach:

//Driver Code Starts #include <bits/stdc++.h> using namespace std;

vector<vector> constructadj(int V, vector<vector> &edges){

vector<vector<int>> adj(V);
for(auto it:edges){
    adj[it[0]].push_back(it[1]);
    adj[it[1]].push_back(it[0]);
}
return adj;

}

//Driver Code Ends

// Helper function for DFS to check bipartite graph bool dfs(int u, int color, vector &colors, vector<vector> &adj) {

// Assign color to the current u
colors[u] = color; 

// Iterate through all adjacent vertices
for(auto &v : adj[u]) {
    if(colors[v] == -1) {

        // Assign alternate color to the adjacent u
        if(!dfs(v, 1 - color, colors, adj))
            return false;
    }
    else if(colors[v] == color) {
      
        // If the adjacent u has the same color,
        // it's not bipartite
        return false;
    }
}
return true;

}

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

// Initialize all vertices as uncolored
vector<int> colors(V, -1); 

// create adjacency list
vector<vector<int>> adj = constructadj(V,edges);

// Check each component of the graph
for(int i = 0; i < V; i++) {

    // If the vertex is uncolored
    if(colors[i] == -1) { 

        // If DFS fails, the graph is not bipartite
        if(!dfs(i, 0, colors, adj))
            return false; 
    }
}

// All vertices can be colored bipartitely
return true;

}

//Driver Code Starts

int main() {

int V = 4;
vector<vector<int>> edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};
if(isBipartite(V, edges))
    cout << "true";
else
    cout << "false";

return 0;

}

//Driver Code Ends

Java

//Driver Code Starts import java.util.*;

class GfG {

// Function to construct the adjacency list from edges
static ArrayList<ArrayList<Integer>> constructadj(int V, int[][] edges) {
    ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
    
    for (int i = 0; i < V; i++) {
        adj.add(new ArrayList<>());
    }

    for (int[] edge : edges) {
        int u = edge[0];
        int v = edge[1];
        adj.get(u).add(v);
        adj.get(v).add(u); 
    }

    return adj;
}

//Driver Code Ends

// Helper function for DFS to check bipartite graph
static boolean dfs(int u, int color, 
             int[] colors, ArrayList<ArrayList<Integer>> adj){
  
    // Assign color to the current u
    colors[u] = color;

    // Iterate through all adjacent vertices
    for (int v : adj.get(u)) {
        if (colors[v] == -1) {

            // Assign alternate color to the adjacent u
            if (!dfs(v, 1 - color, colors, adj))
                return false;
        }
        else if (colors[v] == color) {

            // If the adjacent u has the same color,
            // it's not bipartite
            return false;
        }
    }
    return true;
}

// Function to check if the graph is Bipartite using DFS
static boolean isBipartite(int V, int[][] edges){

    // Initialize all vertices as uncolored
    int[] colors = new int[V];
    Arrays.fill(colors, -1);
    
    // create adjacency list
    ArrayList<ArrayList<Integer>> adj = constructadj(V,edges);
    
    // Check each component of the graph
    for (int i = 0; i < V; i++) {

        // If the vertex is uncolored
        if (colors[i] == -1) {

            // If DFS fails, the graph is not bipartite
            if (!dfs(i, 0, colors, adj))
                return false;
        }
    }

    // All vertices can be colored bipartitely
    return true;
}

//Driver Code Starts public static void main(String[] args) { int V = 4;

    // Edges of the graph
    int[][] edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};

    // Check if the graph is bipartite
    System.out.println(isBipartite(V, edges));
}

} //Driver Code Ends

Python

#Driver Code Starts

Function to construct the adjacency list from edges

def constructadj(V, edges): adj = [[] for _ in range(V)] for edge in edges: u, v = edge adj[u].append(v) adj[v].append(u)
return adj

#Driver Code Ends

def dfs(u, color, colors, adj): # Assign color to the current u colors[u] = color

# Iterate through all adjacent vertices
for v in adj[u]:
    if colors[v] == -1:
        # Assign alternate color to the adjacent u
        if not dfs(v, 1 - color, colors, adj):
            return False
    elif colors[v] == color:
        # If the adjacent u has the same color, it's not bipartite
        return False
return True

def isBipartite(V, edges): # Initialize all vertices as uncolored colors = [-1] * V

# create adjacency list
adj = constructadj(V,edges)

# Check each component of the graph
for i in range(V):
    # If the vertex is uncolored
    if colors[i] == -1:
        # If DFS fails, the graph is not bipartite
        if not dfs(i, 0, colors, adj):
            return False

# All vertices can be colored bipartitely
return True

#Driver Code Starts if name == "main":

V = 4
edges = [[0, 1], [0, 2], [1, 2], [2, 3]]

print("true" if isBipartite(V, edges) else "false")

#Driver Code Ends

C#

//Driver Code Starts using System; using System.Collections.Generic;

class GfG {

public static List<List<int>> constructadj(int V, List<List<int>> edges)
{
    List<List<int>> adj = new List<List<int>>();
    for (int i = 0; i < V; i++)
        adj.Add(new List<int>());

    foreach (var edge in edges)
    {
        int u = edge[0];
        int v = edge[1];
        adj[u].Add(v);
        adj[v].Add(u); 
    }

    return adj;
}

//Driver Code Ends

// Helper function for DFS to check bipartite graph
static bool dfs(int u, int color, int[] colors,
                List<List<int> > adj){

    // Assign color to the current u
    colors[u] = color;

    // Iterate through all adjacent vertices
    foreach(int v in adj[u])
    {
        if (colors[v] == -1) {

            // Assign alternate color to the adjacent u
            if (!dfs(v, 1 - color, colors, adj))
                return false;
        }
        else if (colors[v] == color) {

            // If the adjacent u has the same color,
            // it's not bipartite
            return false;
        }
    }
    return true;
}

// Function to check if the graph is Bipartite using DFS
static bool IsBipartite(int V, List<List<int>> edges){
    // Initialize all vertices as uncolored
    int[] colors = new int[V];
    Array.Fill(colors, -1);
    
    // create adjacency list
    List<List<int>>   adj = constructadj(V, edges);
    
    // Check each component of the graph
    for (int i = 0; i < V; i++) {
        // If the vertex is uncolored
        if (colors[i] == -1) {
            // If DFS fails, the graph is not bipartite
            if (!dfs(i, 0, colors, adj))
                return false;
        }
    }

    // All vertices can be colored bipartitely
    return true;
}

//Driver Code Starts

public static void Main(){
    
    int V = 4;
    List<List<int>> edges = new List<List<int>> {
        new List<int>{0, 1},
        new List<int>{0, 2},
        new List<int>{1, 2},
        new List<int>{2, 3}
    }; 

    if (IsBipartite(V, edges))
        Console.WriteLine("true");
    else
        Console.WriteLine("false");
    
    }

} //Driver Code Ends

JavaScript

//Driver Code Starts // Function to construct adjacency list from edges function constructadj(V, edges) { const adj = Array.from({ length: V }, () => []);

for (const [u, v] of edges) {
    adj[u].push(v);
    adj[v].push(u); // undirected graph
}

return adj;

}

//Driver Code Ends

function dfs(u, color, colors, adj){

// Assign color to the current u
colors[u] = color;

// Iterate through all adjacent vertices
for (let v of adj[u]) {
    if (colors[v] === -1) {
    
        // Assign alternate color to the adjacent u
        if (!dfs(v, 1 - color, colors, adj))
            return false;
    }
    else if (colors[v] === color) {
    
        // If the adjacent u has the same color, it's
        // not bipartite
        return false;
    }
}
return true;

}

// Function to check if the graph is Bipartite using DFS function isBipartite(V, edges){

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

// create adjacency list
let adj  = constructadj(V,edges);

// Check each component of the graph
for (let i = 0; i < V; i++) {

    // If the vertex is uncolored
    if (colors[i] === -1) {
    
        // If DFS fails, the graph is not bipartite
        if (!dfs(i, 0, colors, adj))
            return false;
    }
}

// All vertices can be colored bipartitely
return true;

}

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

let edges = [[0, 1], [0, 2], [1, 2], [2, 3]];

console.log(isBipartite(V, edges)); //Driver Code Ends

`

**Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges. This is because DFS explores each vertex and edge exactly once.
**Auxiliary Space: O(V), for color array and recursion call stack, We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.