思路:graph是邻接矩阵,记录点u的下一个节点v,广度遍历节点进行染色。由于不一定是连通图,所以需要将所有的节点都进行染色,每次先选择一个没上色的节点进行广度遍历上色,直至与这个节点直接或间接相连的点都被上色。
如果不是二分图,则会出现该节点已经有颜色且与要上色的样式不符。
class Solution {
private int RED = 1;
private int GREEN = 2;
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int[] color = new int[n];
Queue<Integer> queue = new LinkedList<>();
for(int i=0;i<n;i++){
if(color[i] == 0){
color[i] = RED;
queue.offer(i);
while(!queue.isEmpty()){
int node = queue.poll();
int neightbor = color[node]!=RED?RED:GREEN;
for(int index:graph[node]){
if(color[index]==0){
color[index] = neightbor;
queue.offer(index);
}
else if(color[index]!=neightbor){
return false;
}
}
}
}
}
return true;
}
}