Check if a given graph is Bipartite using DFS
Given a connected graph, check if the graph is bipartite or not. A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with an even cycle using two colors. For example, see the following graph.
It is not possible to color a cycle graph with an odd cycle using two colors.
In the previous post, an approach using BFS has been discussed. In this post, an approach using DFS has been implemented.
Given below is the algorithm to check for bipartiteness of a graph.
- Use a color[] array which stores 0 or 1 for every node which denotes opposite colors.
- Call the function DFS from any node.
- If the node u has not been visited previously, then assign !color[v] to color[u] and call DFS again to visit nodes connected to u.
- If at any point, color[u] is equal to color[v], then the node is not bipartite.
- Modify the DFS function such that it returns a boolean value at the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void addEdge(vector< int > adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
bool isBipartite(vector< int > adj[], int v,
vector< bool >& visited, vector< int >& color)
{
for ( int u : adj[v]) {
if (visited[u] == false ) {
visited[u] = true ;
color[u] = !color[v];
if (!isBipartite(adj, u, visited, color))
return false ;
}
else if (color[u] == color[v])
return false ;
}
return true ;
}
int main()
{
int N = 6;
vector< int > adj[N + 1];
vector< bool > visited(N + 1);
vector< int > color(N + 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
addEdge(adj, 4, 5);
addEdge(adj, 5, 6);
addEdge(adj, 6, 1);
visited[1] = true ;
color[1] = 0;
if (isBipartite(adj, 1, visited, color)) {
cout << "Graph is Bipartite" ;
}
else {
cout << "Graph is not Bipartite" ;
}
return 0;
}
|
Java
import java.util.*;
class GFG{
static void addEdge(ArrayList<ArrayList<Integer>> adj,
int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static boolean isBipartite(ArrayList<ArrayList<Integer>> adj,
int v, boolean visited[],
int color[])
{
for ( int u : adj.get(v))
{
if (visited[u] == false )
{
visited[u] = true ;
color[u] = 1 - color[v];
if (!isBipartite(adj, u, visited, color))
return false ;
}
else if (color[u] == color[v])
return false ;
}
return true ;
}
public static void main(String args[])
{
int N = 6 ;
ArrayList<
ArrayList<Integer>> adj = new ArrayList<
ArrayList<Integer>>(N + 1 );
for ( int i = 0 ; i <= N; i++)
{
adj.add( new ArrayList<Integer>());
}
boolean visited[] = new boolean [N + 1 ];
int color[] = new int [N + 1 ];
Arrays.fill(color, - 1 );
addEdge(adj, 1 , 2 );
addEdge(adj, 2 , 3 );
addEdge(adj, 3 , 4 );
addEdge(adj, 4 , 5 );
addEdge(adj, 5 , 6 );
addEdge(adj, 6 , 1 );
visited[ 1 ] = true ;
color[ 1 ] = 0 ;
if (isBipartite(adj, 1 , visited, color))
{
System.out.println( "Graph is Bipartite" );
}
else
{
System.out.println( "Graph is not Bipartite" );
}
}
}
|
Python3
def addEdge(adj, u, v):
adj[u].append(v)
adj[v].append(u)
def isBipartite(adj, v, visited, color):
for u in adj[v]:
if (visited[u] = = False ):
visited[u] = True
color[u] = not color[v]
if ( not isBipartite(adj, u,
visited, color)):
return False
elif (color[u] = = color[v]):
return False
return True
if __name__ = = '__main__' :
N = 6
adj = [[] for i in range (N + 1 )]
visited = [ 0 for i in range (N + 1 )]
color = [ 0 for i in range (N + 1 )]
addEdge(adj, 1 , 2 )
addEdge(adj, 2 , 3 )
addEdge(adj, 3 , 4 )
addEdge(adj, 4 , 5 )
addEdge(adj, 5 , 6 )
addEdge(adj, 6 , 1 )
visited[ 1 ] = True
color[ 1 ] = 0
if (isBipartite(adj, 1 , visited, color)):
print ( "Graph is Bipartite" )
else :
print ( "Graph is not Bipartite" )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void addEdge(List<List< int >> adj,
int u, int v)
{
adj[u].Add(v);
adj[v].Add(u);
}
static bool isBipartite(List<List< int >> adj,
int v, bool []visited,
int []color)
{
foreach ( int u in adj[v])
{
if (visited[u] == false )
{
visited[u] = true ;
color[u] = 1 - color[v];
if (!isBipartite(adj, u, visited, color))
return false ;
}
else if (color[u] == color[v])
return false ;
}
return true ;
}
public static void Main(String []args)
{
int N = 6;
List<List< int >> adj = new List<List< int >>(N + 1);
for ( int i = 0; i <= N; i++)
{
adj.Add( new List< int >());
}
bool []visited = new bool [N + 1];
int []color = new int [N + 1];
for ( int i = 0; i <= N; i++)
color[i] = -1;
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
addEdge(adj, 4, 5);
addEdge(adj, 5, 6);
addEdge(adj, 6, 1);
visited[1] = true ;
color[1] = 0;
if (isBipartite(adj, 1, visited, color))
{
Console.WriteLine( "Graph is Bipartite" );
}
else
{
Console.WriteLine( "Graph is not Bipartite" );
}
}
}
|
Javascript
<script>
function addEdge(adj, u, v)
{
adj[u].push(v);
adj[v].push(u);
}
function isBipartite(adj, v, visited, color)
{
adj[v].forEach(u => {
if (visited[u] == false ) {
visited[u] = true ;
color[u] = !color[v];
if (!isBipartite(adj, u, visited, color))
return false ;
}
else if (color[u] == color[v])
return false ;
});
return true ;
}
var N = 6;
var adj = Array.from(Array(N+1), ()=>Array());
var visited = Array(N+1);;
var color = Array(N+1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
addEdge(adj, 4, 5);
addEdge(adj, 5, 6);
addEdge(adj, 6, 1);
visited[1] = true ;
color[1] = 0;
if (isBipartite(adj, 1, visited, color)) {
document.write( "Graph is Bipartite" );
}
else {
document.write( "Graph is not Bipartite" );
}
</script>
|
Output
Graph is Bipartite
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Last Updated :
29 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...