Skip to content

Commit dee4727

Browse files
Added Is a Graph Bipartite Algorithm
1 parent f0fb971 commit dee4727

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+
package com.thealgorithms.graph;
2+
3+
import java.util.*; // For ArrayList, Queue, LinkedList
4+
5+
public class IsGraphBipartite {
6+
// Inner class to represent an edge
7+
class Edge {
8+
int src;
9+
int dest;
10+
11+
public Edge(int s, int d) {
12+
this.src = s;
13+
this.dest = d;
14+
}
15+
}
16+
17+
// Function to check if a graph is bipartite
18+
public static boolean isbipartite(ArrayList<Edge>[] graph) {
19+
int col[] = new int[graph.length];
20+
Arrays.fill(col, -1); // initialize all vertices with -1 (uncolored)
21+
22+
Queue<Integer> q = new LinkedList<>();
23+
24+
for (int i = 0; i < graph.length; i++) {
25+
if (col[i] == -1) { // unvisited node
26+
q.add(i);
27+
col[i] = 0; // assign first color
28+
29+
while (!q.isEmpty()) {
30+
int curr = q.remove();
31+
for (int j = 0; j < graph[curr].size(); j++) {
32+
Edge e = graph[curr].get(j);
33+
34+
if (col[e.dest] == -1) {
35+
int nextCol = (col[curr] == 0) ? 1 : 0;
36+
col[e.dest] = nextCol;
37+
q.add(e.dest);
38+
} else if (col[e.dest] == col[curr]) {
39+
return false; // same color conflict
40+
}
41+
}
42+
}
43+
}
44+
}
45+
return true;
46+
}
47+
48+
// Converts adjacency list (int[][]) to Edge-based graph and checks bipartiteness
49+
public boolean isBipartite(int[][] graph) {
50+
ArrayList<Edge>[] graph2 = new ArrayList[graph.length];
51+
for (int i = 0; i < graph2.length; i++) {
52+
graph2[i] = new ArrayList<>();
53+
}
54+
55+
for (int i = 0; i < graph.length; i++) {
56+
for (int j = 0; j < graph[i].length; j++) {
57+
int neighbor = graph[i][j];
58+
graph2[i].add(new Edge(i, neighbor));
59+
}
60+
}
61+
62+
return isbipartite(graph2);
63+
}
64+
65+
// Test the function
66+
public static void main(String[] args) {
67+
IsGraphBipartite sol = new IsGraphBipartite();
68+
69+
// Example 1: Bipartite graph
70+
int[][] graph1 = {
71+
{1, 3},
72+
{0, 2},
73+
{1, 3},
74+
{0, 2}
75+
};
76+
System.out.println("Graph 1 is bipartite: " + sol.isBipartite(graph1)); // true
77+
78+
// Example 2: Non-bipartite graph (odd cycle)
79+
int[][] graph2 = {
80+
{1, 2},
81+
{0, 2},
82+
{0, 1}
83+
};
84+
System.out.println("Graph 2 is bipartite: " + sol.isBipartite(graph2)); // false
85+
}
86+
}

0 commit comments

Comments
 (0)