二分图判定有两点。
1、图为连通图。
2、可以分为两个不同的点集。
二分图的另一种等价的说法是,可以把每个节点着以黑色和白色之一,使得每条边的两个端点颜色不同.不难发现,非连通的图是二分图当且仅当每个连通分量都是二分图,因此我们只考虑无向连通图。
连通图判断方式
#include<cstdio>
#include<algorithm>
#define N 42000
int next[N],to[N],num,head[N],col[N],flag,n,m,a,b;
void add(int false_from,int false_to){
next[++num]=head[false_from];
to[num]=false_to;
head[false_from]=num;
}
void dfs(int x,int color){
col[x]=color;
for(int i=head[x];i;i=next[i]){
if(col[to[i]]==col[x]){
printf("NO");
flag=1;
exit(0);
}
if(!col[to[i]])
dfs(to[i],-color);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i){
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
dfs(1,1);
if(!flag)
printf("YES");
return 0;
}
非连通图判断方式。
#include<cstdio>
#include<algorithm>
#define N 42000
int next[N],to[N],num,head[N],col[N],flag,n,m,a,b;
void add(int false_from,int false_to){
next[++num]=head[false_from];
to[num]=false_to;
head[false_from]=num;
}
void dfs(int x,int color){
col[x]=color;
for(int i=head[x];i;i=next[i]){
if(col[to[i]]==col[x]){
printf("NO");
flag=1;
exit(0);
}
if(!col[to[i]])
dfs(to[i],-color);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i){
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
for(int i=1;i<=n&&!flag;++i)
if(!col[i])
dfs(i,1);
if(!flag)
printf("YES");
return 0;
}