Bipartite Graph
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int[] colors = new int[n];
for (int i = 0; i < n; i++) {
if (colors[i] == 0 && !dfs(i, 1, colors, graph)) {
return false;
}
}
return true;
}
private boolean dfs(int curt, int color, int[] colors, int[][] graph) {
if (colors[curt] != 0) {
return colors[curt] == color;
}
colors[curt] = color;
for (int next : graph[curt]) {
if (!dfs(next, -color, colors, graph)) {
return false;
}
}
return true;
}Last updated