【问题标题】:using dfs to check if graph is bipartite使用 dfs 检查图是否为二分图
【发布时间】:2021-09-25 05:34:24
【问题描述】:

class graph{
    void DFSutil(int v);

    public:
        
        map<int, vector<int> > adj;
        map<int, bool> visited;
        map<int, int> color;
        int twoteams = 1;
        
        void DFS();
        void addEdge(int u,int v);
        
        
};

此函数将边添加到图形中


void graph::addEdge(int u,int v){
    
    adj[u].push_back(v);
    
}

深度优先搜索功能。 我试图将孩子着色为 !parent (如果我没有错): 如果孩子和父母的颜色相同,则表示该图不是二分图


void graph::DFSutil(int v){
    
    visited[v] = true;
    
    for (auto i:adj[v]){
        if(visited[i]==false){
            
            color[i] = !color[v];
            DFSutil(i);
            
        }
        else if(color[i]==color[v]){
            
        twoteams = 0;
        return;
        }
    }
}

如果图有多个连通分量

void graph::DFS(){
    
    for (auto i:adj){
        if(!visited[i.first]) DFSutil(i.first);
    }
    
}

图形被给出为:B(一个向量):[[1,2],[1,3]...] 边:1-->2, 1-->3...

int Solution::solve(int A, vector<vector<int> > &B) {
    
    graph g;
    g.addEdge(B[0][0],B[0][1]);
    g.color[B[0][0]] = 1;
    int n = B.size();
    for (int i=1;i<n;++i){
        
        g.addEdge(B[i][0],B[i][1]);
        
    }
    g.DFS();
    return g.twoteams;
}

为什么它不检查图形是否是二分的。 color 将节点的颜色存储为 0 或 1; 如果不是二分的,它应该返回 0,否则返回 1

【问题讨论】:

    标签: c++ graph-theory directed-graph


    【解决方案1】:

    要确定一个图是否是二分图,确定最大团的数量正好是两个就足够了。

    这是寻找最大团的伪代码

    LOOP
        CONSTRUCT empty current set
        SELECT V arbitrary vertex
        add V to current set
        remove V from graph
        LOOP      // while set is growing
            added_to_set = false
            LOOP V over vertices in graph
                LOOP Vset over current set
                    IF Vset connected to V
                         add V to current set
                         remove V from graph
                         added_to_set = true
                         break;
            IF added_to_set == false
               break;    // the set is maximal
        ADD current set to list of sets
        IF graph has no remaining vertices
           OUTPUT sets found
           STOP
    

    有关此代码的 C++ 实现,请参阅https://github.com/JamesBremner/PathFinder2/blob/dbd6ff06edabd6a6d35d5eb10ed7972dc2d779a6/src/cPathFinder.cpp#L483 处的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      相关资源
      最近更新 更多