维护一个一维数组color[],记录每个点的颜色。创建时的默认值0代表尚未被涂色,1代表红色,-1代表蓝色。最外圈的for循环每一次代表一次BFS。如果这是一个连通图(Connected Graph),那么只循环1次就能完成给所有点上色。如果这是一个非连通图(Disconnected Graph),则循环次数等于connected component的个数。在每个点加入队列时给其上色。在出队时,逐个检查他的邻居,如果尚未被涂色则涂上相反的颜色并加入队列;如果已被涂色且与当前颜色相同,则返回false。https://www.tutorialspoint.com/connected-vs-disconnected-graphs
代码如下:
class Solution {
public boolean isBipartite(int[][] graph) {
int length = graph.length;
int[] color = new int[length];
// If it is a connected graph, we will only iterate 1 round.
// If it is a diconnected graph, we have to iterate at least 2 rounds.
for(int i = 0; i < length; i++){
// Check whether this node has been visited previously.
// This step is designed for a disconnected graph.
if(color[i] != 0){
continue;
}
Queue<Integer> queue = new LinkedList<>();
queue.offer(i);
color[i] = 1;
while(!queue.isEmpty()){
int curr = queue.poll();
for(int next: graph[curr]){
if(color[next] == 0){
color[next] = -color[curr];
queue.offer(next);
}else if(color[next] == color[curr]){
return false;
}
}
}
}
return true;
}
}