图论 - 二分图的判断(dfs染色法)

二分图的判断(dfs染色法)

如何判断一个图是否为二分图
普通染色法模板
C++ 代码模板如下

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
const int inf = 1000;
int V, E;
vector<int> G[inf];
int color[inf];
bool dfs(int node, int col)
{
    color[node] = col; //染色
    for (int i = 0; i < G[node].size; i++)
    {
        //如果相邻的顶点同色,就剪掉这一枝,返回false
        if (color[G[node][i]] == col)
            return false;
        if (color[G[node][i]] == 0 && dfs(G[node][i],-col))
            return false;
    }
    //如果都染了色返回true
    return true;
}
void dfsTrave()
{
    for (int i = 0; i < V; i++)
    {
        if (color[i] == 0)
        {
            if (!dfs(i, 1))
            {
                cout << "No" << endl;
                return;
            }
        }
    }
    cout << "Yes" << endl;
}
int main()
{
    cin >> V >> E;
    int a, b;
    for (int i = 0; i < E; i++)
    {
        cin >> a >> b;
        G[a].push_back(b); //无向图存储两次 
        G[b].push_back(a); //如果是有向图只用存储一次即可
    }
    dfsTrave();
    system("pause");
    return 0;
}

如果大家有什么疑问的话可以加qq向我提出哦,欢迎各位大佬指出问题。
如果你觉得对你有所帮助的话就给我点个赞,点燃我下次写文章的动力吧 ^_^

猜你喜欢

转载自www.cnblogs.com/wlw-x/p/11592431.html
今日推荐