Skip to content

Commit e44af78

Browse files
committed
☀️ Bipartite Graph
1 parent b7ed199 commit e44af78

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

Graph Algorithms/Bipartite.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
* A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V
3+
* such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U.
4+
* In other words, for every edge (u, v), either u belongs to U and v to V,
5+
* or u belongs to V and v to U.
6+
* We can also say that there is no edge that connects vertices of same set.
7+
*
8+
*
9+
* Time Complexity of the above approach is same as that Breadth First Search.
10+
* O(V^2) where V is number of vertices.
11+
* If graph is represented using adjacency list,
12+
* then the complexity becomes O(V+E).
13+
*/
14+
15+
16+
import java.util.*;
17+
import java.io.*;
18+
19+
class Bipartite {
20+
21+
public static boolean isBipartiteUtil(int G[][], int index, int colorArray[], int V) {
22+
23+
colorArray[index] = 1;
24+
25+
LinkedList<Integer> queue = new LinkedList<Integer>();
26+
27+
queue.add(index);
28+
29+
while (!queue.isEmpty()) {
30+
31+
int elem = queue.pop();
32+
33+
if (G[elem][elem] == 1) {
34+
return false;
35+
}
36+
37+
for (int i = 0; i < V; i++) {
38+
39+
if (G[elem][i] == 1 && colorArray[i] == -1) {
40+
41+
colorArray[i] = 1 - colorArray[elem];
42+
queue.push(i);
43+
}
44+
45+
else if(G[elem][i] == 1 && colorArray[i] == colorArray[elem]){
46+
return false;
47+
}
48+
}
49+
}
50+
51+
return true;
52+
}
53+
54+
public static boolean isBipartite(int V, int G[][]) {
55+
56+
int[] colorArray = new int[V];
57+
Arrays.fill(colorArray, -1);
58+
59+
for (int i = 0; i < V; i++) {
60+
if (colorArray[i] == -1) {
61+
if (isBipartiteUtil(G, i, colorArray, V) == false) {
62+
return false;
63+
}
64+
}
65+
}
66+
return true;
67+
}
68+
69+
public static void main(String[] args) {
70+
71+
int G[][] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; // Adjacency Matrix
72+
int V = 4; // Vertices
73+
74+
if (isBipartite(V, G))
75+
System.out.println("Yes, the graph is bipartite.");
76+
else
77+
System.out.println("No, it's not!");
78+
}
79+
}

0 commit comments

Comments
 (0)