Skip to content

Commit 1f89b5b

Browse files
committed
Add Graphs/785_Is_Graph_Bipartite?.java
1 parent 19c4e23 commit 1f89b5b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Graphs/785_Is_Graph_Bipartite?.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public boolean isBipartite(int[][] graph) {
3+
int[] colours = new int[graph.length];
4+
5+
for (int i = 0; i < graph.length; i++) {
6+
if (colours[i] == 0 && !hasValidColour(graph, colours, i, 1)) {
7+
return false;
8+
}
9+
}
10+
11+
return true;
12+
}
13+
14+
private boolean hasValidColour(int[][] graph, int[] colours, int idx, int colour) {
15+
if (colours[idx] != 0) {
16+
return colours[idx] == colour;
17+
}
18+
19+
colours[idx] = colour;
20+
21+
for (int neighbour : graph[idx]) {
22+
if (!hasValidColour(graph, colours, neighbour, -colour)) {
23+
return false;
24+
}
25+
}
26+
27+
return true;
28+
}
29+
}

0 commit comments

Comments
 (0)