-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathIsGraphBipartite.java
More file actions
33 lines (33 loc) · 980 Bytes
/
IsGraphBipartite.java
File metadata and controls
33 lines (33 loc) · 980 Bytes
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
class Solution {
// depth first search
public boolean color(int src, int graph[][], int color[]){
Queue<Integer> queue = new LinkedList<>();
queue.offer(src);
color[src] = 0;
while(!queue.isEmpty()){
int node = queue.poll();
for(int neighbour : graph[node]){
if(color[neighbour]==-1){
color[neighbour] = 1 - color[node];
queue.offer(neighbour);
}else if(color[neighbour] == color[node]){
return false;
}
}
}
return true;
}
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int color[] = new int[n];
Arrays.fill(color,-1);
for(int i=0;i<n;i++){
if(color[i] == -1){
if(!color(i,graph,color)){
return false;
}
}
}
return true;
}
}