-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathIsGraphBipartite.java
More file actions
46 lines (32 loc) · 1.38 KB
/
IsGraphBipartite.java
File metadata and controls
46 lines (32 loc) · 1.38 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
39
40
41
42
43
44
45
46
// @saorav21994
// Graph coloring method (k = 2 for bipartite). Try to assign alternating color to parent and child. If not possible at any point return false.
// TC : O(V+E)
// SC : O(V)
class Solution {
public boolean isBipartite(int[][] graph) {
int v = graph.length;
int [] color = new int[v];
Arrays.fill(color, -1);
int curColor = 0;
for (int i = 0; i < v; i++) {
if (color[i] == -1) // not visited / colored
if (!dfs(graph, color, i, (curColor+1)%2))
return false;
}
return true;
}
public boolean dfs(int [][] graph, int [] color, int vertex, int curColor) {
if (color[vertex] != -1 && color[vertex] != curColor) // parent color same as child
return false;
if (color[vertex] != - 1) // color assigned already and is correct for bipartite
return true;
// color[vertex] = -1 -> unassigned, so assign it
color[vertex] = curColor;
// Repeat for all connected vertex of current vertex (basically for all edges of current vertex)
for (int neiVertex : graph[vertex]) {
if (!dfs(graph, color, neiVertex, (curColor+1)%2))
return false;
}
return true;
}
}