编写程序以检查图形是否为二分图

时间:2010-05-22 17:23:06

标签: algorithm graph bipartite

我需要编写一个程序来检查图表是否为二分图。

我已阅读有关graph coloringbipartite graph的维基百科文章。这两篇文章提出了像BFS搜索一样测试二分性的方法,但我不能编写实现这些方法的程序。

3 个答案:

答案 0 :(得分:12)

你为什么不能?你的问题让人甚至很难为你编写程序,因为你甚至没有提到特定的语言......

我们的想法是首先将一个随机节点放入FIFO队列(也是here)。颜色为蓝色。然后在队列中仍有节点的情况下重复此操作:将元素出列。使用与提取的元素不同的颜色为其邻居着色,并将每个邻居插入(入队)到FIFO队列中。例如,如果您将一个红色的元素(节点)出列(提取),则将其邻居的颜色设置为蓝色。如果提取蓝色节点,则将其邻居的颜色设置为红色。如果没有着色冲突,则图表是二分的。如果你最终用两种不同的颜色着色节点,那么它不是二分的。

就像@Moron所说,我所描述的只适用于连接图。但是,您可以对每个连接的组件应用相同的算法,以使其适用于任何图形。

答案 1 :(得分:1)

http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/breadthSearch.htm

请阅读此网页,使用广度优先搜索来检查您何时找到某个节点,检查当前周期是奇数还是偶数。

当且仅当它不包含奇数周期时,图是二分的。

答案 2 :(得分:1)

具体实现如下(C ++版):

struct NODE
{
    int color;
    vector<int> neigh_list;
};

bool checkAllNodesVisited(NODE *graph, int numNodes, int & index);

bool checkBigraph(NODE * graph, int numNodes)
{
    int start = 0;

    do 
    {
        queue<int> Myqueue;
        Myqueue.push(start);
        graph[start].color = 0;

        while(!Myqueue.empty())
        {
            int gid = Myqueue.front();
            for(int i=0; i<graph[gid].neigh_list.size(); i++)
            {
                int neighid = graph[gid].neigh_list[i];
                if(graph[neighid].color == -1)
                {
                    graph[neighid].color = (graph[gid].color+1)%2; // assign to another group
                    Myqueue.push(neighid);
                }
                else
                {
                    if(graph[neighid].color == graph[gid].color) // touble pair in the same group
                        return false;
                }
            }
            Myqueue.pop();
        }
    } while (!checkAllNodesVisited(graph, numNodes, start)); // make sure all nodes visited 
                                            // to be able to handle several separated graphs, IMPORTANT!!!

    return true;
}

bool checkAllNodesVisited(NODE *graph, int numNodes, int & index)
{
    for (int i=0; i<numNodes; i++)
    {
        if (graph[i].color == -1)
        {
            index = i;
            return false;
        }
    }

    return true;
}