Skip to content

Commit 5d15d96

Browse files
committed
doing a dfs and checking if neighbours are opposite colour
1 parent 3f64635 commit 5d15d96

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

DFS/isBipartite.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public boolean isBipartite(int[][] graph) {
3+
/*
4+
we have to colour the nodes such that the next node is of different colour.
5+
basically index position in graph array is parent and the array elements is
6+
the neighbours. So, ith position we colour by 1 and its neighbour we try to
7+
colour differently. We note the colour in colours array.
8+
9+
O(n) time complexity
10+
*/
11+
int nodes = graph.length; // number of nodes
12+
int[] colours = new int[nodes]; // to keep track whether the node is coloured or not
13+
14+
for (int i=0; i<graph.length; i++) {
15+
if ((colours[i] == 0) && (!dfs(graph, colours, 1, i)) ) { // if it's not coloured and we can't colour it.
16+
return false;
17+
}
18+
}
19+
return true;
20+
}
21+
// utility function which will tell if we can colour the node.
22+
public boolean dfs(int[][] graph, int[] colours, int colour, int node) {
23+
if (colours[node] != 0) { // if the node is already coloured
24+
return (colours[node] == colour); // check if it is of the colour we want.
25+
} else {
26+
colours[node] = colour; // colour the node with the colour
27+
for (int neighbour: graph[node]) { // try to colour it neighbours
28+
if (!dfs(graph, colours, -colour, neighbour)) { // if we can't colour the neighbour to opposite colour
29+
return false; // return false if we can't colour it opposite.
30+
}
31+
}
32+
}
33+
return true;
34+
}
35+
}

0 commit comments

Comments
 (0)