dfs染色法判定二分图

#include<iostream>
#include<cstring>
using namespace std;
int mapp[2005][2005],color[2005],n;
int dfs(int x,int c)
{
    color[x]=c;
    for(int i=1;i<=n;i++)
    {
        if(mapp[x][i]==1)
        {
            if(color[i]==c)
                return 0;
            if(color[i]==0&&!dfs(i,-c))
                return 0;
        }
    }
    return 1;
}
int main()
{
    int T,m,x,flag,y,g;
    cin>>T;
    while(T--)
    {
        cin>>n>>m;
        memset(mapp,0,sizeof(mapp));
        memset(color,0,sizeof(color));
        for(int i=1;i<=m;i++)
        {
            cin>>x>>y;
            mapp[x][y]=1;
            mapp[y][x]=1;
        }
        flag=0;
        for(int i=1;i<=n;i++)
        {
            if(color[i]==0&&!dfs(i,1))
            {
                flag=1;
                break;
            }
        }
        if(flag==1)
        {
            cout<<"No"<<endl;
        }
        else
        {
            cout<<"Yes"<<endl;
        }
    }
}
原文地址:https://www.cnblogs.com/Leozi/p/10835007.html