Skip to content

Commit 30ae660

Browse files
committed
add: BipartiteGraphValidation
1 parent 8f239f6 commit 30ae660

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class BipartiteGraphValidation {
2+
public boolean bipartiteGraphValidation(int[][] graph) {
3+
int[] colors = new int[graph.length];
4+
// Determine if each graph component is bipartite.
5+
for (int i = 0; i < graph.length; i++) {
6+
if (colors[i] == 0 && !dfs(i, 1, graph, colors)) {
7+
return false;
8+
}
9+
}
10+
return true;
11+
}
12+
13+
private boolean dfs(int node, int color, int[][] graph, int[] colors) {
14+
colors[node] = color;
15+
for (int neighbor : graph[node]) {
16+
// If the current neighbor has the same color as the current
17+
// node, the graph is not bipartite.
18+
if (colors[neighbor] == color) {
19+
return false;
20+
}
21+
// If the current neighbor is not colored, color it with the
22+
// other color and continue the DFS.
23+
if (colors[neighbor] == 0 && !dfs(neighbor, -color, graph, colors)) {
24+
return false;
25+
}
26+
}
27+
return true;
28+
}
29+
}

0 commit comments

Comments
 (0)