给定一个无向图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}
这题bfs/dfs 都可以,判断二分图,给结点x着色,对于x的邻接点着相反的色... ...
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
int len=graph.size();
///graph 无向图
int color[len];
memset(color,-1,len*sizeof(int));
queue<int> qu;
for(int start=0;start<len;start++){
if(color[start]==-1){ //遍历所有的连通分量
qu.push(start);
color[start]=0;
while(!qu.empty()){ //1个连通分量
int cur=qu.front();qu.pop();
for(int x:graph[cur]){
if(color[x]==-1){
color[x]=color[cur]^1;
qu.push(x);
}else if(color[x]==color[cur]){
return false;
}
}
}
}
}
return true;
}
};
dfs:31% 5%
class Solution {
private:
int len;
int *color;
bool ans;
public:
void dfs(int node,vector<vector<int>>& graph){
if(graph[node].size()==0){
ans=true;
return ;
}
for(int x:graph[node]){
if(color[x]==-1){
color[x]=color[node]^1;
dfs(x,graph);
if(!ans) return ;
}else if(color[x]==color[node]){
ans=false;
return;
}
}
ans=true;
}
bool isBipartite(vector<vector<int>>& graph) {
len=graph.size();
color=new int[len];
memset(color,-1,len*sizeof(int));
for(int start=0;start<len;start++){
if(color[start]==-1){
color[start]=0;
dfs(start,graph);
if(!ans) break;
}
}
return ans;
}
};