题目链接:判断是否为二分图
题目描述:
给定一个无向图graph,当这个图为二分图时返回true。
如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。
graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
示例 1:
输入: [[1,3], [0,2], [1,3], [0,2]]
输出: true
解释:
无向图如下:
0----1
| |
| |
3----2
我们可以将节点分成两组: {0, 2} 和 {1, 3}。
示例 2:
输入: [[1,2,3], [0,2], [0,1,3], [0,2]]
输出: false
解释:
无向图如下:
0----1
| \ |
| \ |
3----2
我们不能将节点分割成两个独立的子集。
注意:
graph 的长度范围为 [1, 100]。
graph[i] 中的元素的范围为 [0, graph.length - 1]。
graph[i] 不会包含 i 或者有重复的值。
图是无向的: 如果j 在 graph[i]里边, 那么 i 也会在 graph[j]里边。
题目分析:将顶点集合分为两个没有交集的集合,使得任意边的两个顶点分别在这两个集合里面,我们可以通过染色,即标记顶点的状态来做到,最后所有顶点被分为2种不同的状态,并且所有顶点均被访问到。
具体为:从任意一个未被访问的顶点出发,对它标记黑色,然后对它能到达的顶点染白色,代表属于两个不同的集合,如果访问的顶点已经被染色并且不是它应该染的颜色,证明有条边不是属于2个独立的集合(2个集合存在交集),属于非二分图的情况。这个标记过程其实就是遍历图的过程,使用dfs,bfs均可
bfs
class Solution {
public boolean isBipartite(int[][] graph) {
int n = graph.length;
//定义-1表示未染色,0代表黑色,1代表白色
int[] color = new int[n];
Arrays.fill(color, -1);//初始均为未染色
//非连通图都要遍历一遍
for(int i = 0;i < n;i++){
if(color[i] == -1){//为染色进行染色
Queue<Integer> q = new LinkedList<>();
q.offer(i);
color[i] = 0;//染黑色
while(!q.isEmpty()){
int cur = q.poll();
//直达的孩子节点染成相反的白色
int nextColor = color[cur] == 0?1:0;
for (int child : graph[cur]) {
if(color[child] == -1){
color[child] = nextColor;
q.offer(child);
}else{//孩子节点若是与将要染的颜色不同,则失败
if(color[child] != nextColor) return false;
}
}
}
}
}
return true;
}
}
dfs
class Solution {
public int[] color;
boolean ans;
public boolean isBipartite(int[][] graph) {
int n = graph.length;
//定义-1表示未染色,0代表黑色,1代表白色
color = new int[n];
ans = true;
Arrays.fill(color, -1);//初始均为未染色
//非连通图都要遍历一遍
for(int i = 0;i < n;i++){
if(color[i] == -1){
dfs(i,0,graph);
}
}
return ans;
}
public void dfs(int i,int c,int[][] graph) {
color[i] = c;
int nextColor = c == 0?1:0;
for(int child:graph[i]){//孩子节点染相反的颜色
if(color[child] == -1){
dfs(child,nextColor,graph);
if(!ans) return;
}else {
if(color[child] != nextColor){
ans = false;
return;
}
}
}
}
}