判断一个图是否为二分图

转载自:http://blog.csdn.net/joy_go/article/details/8567069

怎样判断一个图是否为二分图?

很简单,用染色法,即从其中一个顶点开始,将跟它邻接的点染成与其不同的颜色,如果邻接的点有相同颜色的,则说明不是二分图,每次用bfs遍历即可。

[cpp]  view plain  copy
  1. #include <queue>  
  2. #include <cstring>  
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. const int N = 510;  
  7. int color[N], graph[N][N];  
  8.   
  9. //0为白色,1为黑色   
  10. bool bfs(int s, int n) {  
  11.     queue<int> q;  
  12.     q.push(s);  
  13.     color[s] = 1;  
  14.     while(!q.empty()) {  
  15.         int from = q.front();  
  16.         q.pop();  
  17.         for(int i = 1; i <= n; i++) {  
  18.             if(graph[from][i] && color[i] == -1) {  
  19.                 q.push(i);  
  20.                 color[i] = !color[from];//染成不同的颜色   
  21.             }  
  22.             if(graph[from][i] && color[from] == color[i])//颜色有相同,则不是二分图   
  23.                 return false;  
  24.         }  
  25.     }  
  26.     return true;       
  27. }  
  28.   
  29. int main() {  
  30.     int n, m, a, b, i;  
  31.     memset(color, -1, sizeof(color));  
  32.     cin >> n >> m;  
  33.     for(i = 0; i < m; i++) {  
  34.         cin >> a >> b;  
  35.         graph[a][b] = graph[b][a] = 1;   
  36.     }  
  37.     bool flag = false;  
  38.     for(i = 1; i <= n; i++)  
  39.         if(color[i] == -1 && !bfs(i, n)) {//遍历各个连通分支   
  40.             flag = true;  
  41.             break;    
  42.         }  
  43.     if(flag)  
  44.         cout << "NO" <<endl;      
  45.     else  
  46.         cout << "YES" <<endl;  
  47.     return 0;  
  48. }  
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值