Skip to main content

Leetcode 785

· One min read
Junhe Chen

Simple graph coloring question.

class Solution {
public boolean isBipartite(int[][] graph) {
// graph color
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(!isBipartite(graph,i,color)){
return false;
}
}
}
return true;
}
private boolean isBipartite(int[][] graph, int curr, int[] color){
Queue<Integer> q = new LinkedList<>();
color[curr] = 1; // color curr node to 1
q.add(curr);
while(!q.isEmpty()){
int c = q.poll();
for(int next : graph[c]){
if(color[next] == color[c]) return false;
if(color[next] == -1){
// this is not colored yet
color[next] = 1 - color[c];
q.add(next);
}
}
}
return true;
}
}