-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_3_Graph_Bipartite.java
More file actions
38 lines (32 loc) · 1.24 KB
/
Problem_3_Graph_Bipartite.java
File metadata and controls
38 lines (32 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package Union_Find;
// Problem Statement: Is Graph Bipartite? (medium)
// LeetCode Question: 785. Is Graph Bipartite?
public class Problem_3_Graph_Bipartite {
private int[] parent;
public boolean isBipartite(int[][] graph) {
parent = new int[graph.length];
for (int i = 0; i < graph.length; i++) {
parent[i] = i;
}
for (int u = 0; u < graph.length; u++) {
if (graph[u].length == 0) continue; // No edges for this node
int parentU = find(u); // Find the parent set for u
int firstNeighbor = graph[u][0]; // Take the first neighbor
// Union the rest of u's neighbors to the first neighbor's set
for (int v : graph[u]) {
if (parentU == find(v)) return false; // If u and v belong to the same set
union(firstNeighbor, v); // Union v with the first neighbor
}
}
return true;
}
private int find(int node) {
if (parent[node] != node) {
parent[node] = find(parent[node]); // Path compression
}
return parent[node];
}
private void union(int node1, int node2) {
parent[find(node1)] = find(node2); // Union by updating the parent
}
}