Skip to content

Commit 391c0a4

Browse files
committed
Bipartite Graph BFS
1 parent 41282ca commit 391c0a4

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import java.util.ArrayList;
2+
import java.util.Queue;
3+
import java.util.LinkedList;
4+
5+
public class GraphsP2_Bipartite {
6+
static class Edge {
7+
int src, dest;
8+
9+
public Edge(int src, int dest) {
10+
this.src = src;
11+
this.dest = dest;
12+
}
13+
}
14+
15+
static void createGraph(ArrayList<Edge>[] graph) {
16+
/*
17+
* 1 ———— 0 ———— 2
18+
* \ /
19+
* \ /
20+
* 3 ————— 4
21+
*/
22+
for (int i = 0; i < graph.length; i++) {
23+
graph[i] = new ArrayList<>();
24+
}
25+
graph[0].add(new Edge(0, 1));
26+
graph[0].add(new Edge(0, 2));
27+
28+
graph[1].add(new Edge(1, 0));
29+
graph[1].add(new Edge(1, 3));
30+
31+
graph[2].add(new Edge(2, 0));
32+
graph[2].add(new Edge(2, 4));
33+
34+
graph[3].add(new Edge(3, 1));
35+
graph[3].add(new Edge(3, 4));
36+
37+
graph[4].add(new Edge(4, 2));
38+
graph[4].add(new Edge(4, 3));
39+
}
40+
41+
// Bipartite Graph BFS -------------------------------- TC -> O(V+E) & SC -> O(V) where V is vertex & E is edge
42+
public static boolean isBipartiteGraph(ArrayList<Edge>[] graph) {
43+
int[] colors = new int[graph.length];
44+
for (int i = 0; i < colors.length; i++) {
45+
colors[i] = -1; // no colors
46+
}
47+
for (int i = 0; i < graph.length; i++) {
48+
if (colors[i] == -1) {
49+
if (isBipartiteGraphUtil(graph, i, colors)) {
50+
return true;
51+
}
52+
}
53+
}
54+
return false;
55+
}
56+
57+
public static boolean isBipartiteGraphUtil(ArrayList<Edge>[] graph, int curr, int[] colors) { // BSF
58+
Queue<Integer> q = new LinkedList<>();
59+
q.add(curr); // add in queue
60+
colors[curr] = 0; // add color (Yellow)
61+
while (!q.isEmpty()) {
62+
curr = q.remove();
63+
for (int level = 0; level < graph[curr].size(); level++) { // current Edge neighbor traversal
64+
Edge e = graph[curr].get(level);
65+
if (colors[e.dest] == colors[curr]) { // same color
66+
return false;
67+
} else if (colors[e.dest] == -1) { // add color
68+
q.add(e.dest);
69+
colors[e.dest] = (colors[curr] == 0) ? 1 : 0;
70+
}
71+
// deffered color -> continue
72+
}
73+
}
74+
return true;
75+
}
76+
77+
public static void main(String[] args) {
78+
// Bipartite Graph --------------------------------
79+
// If graph doesn't have cycle -> Bipartite Graph (true)
80+
int V = 5;
81+
@SuppressWarnings("unchecked") // Remove unnecessary warnings
82+
ArrayList<Edge>[] graph = new ArrayList[V];
83+
createGraph(graph);
84+
System.out.println("Is Bipartite graph : " + isBipartiteGraph(graph));
85+
}
86+
}

0 commit comments

Comments
 (0)