使用 bfs 着色算法来检查图形在 Python 中是否是二分图



代码:

def bipartite(G):
    open_list = [1]
    colors = {}
    color_counter = 0
    # assign a color to the first node being visited
    colors[1] = 0
    while open_list:
        # up the counter here so that all neighbors get the same color
        color_counter += 1
        # use first elem for bfs
        current_neighbors = G[open_list[0]]
        current_color = color_counter % 2
        # prints used for debugging
        print open_list
        print "The current color is: %s" % (current_color,)
        for neighbor in current_neighbors:
            if neighbor not in colors:
                open_list.append(neighbor)
                colors[neighbor] = current_color
                # print used for debugging
                print "parent is: %s, child is: %s, %s's color is: %s" 
                % (open_list[0], neighbor, neighbor, colors[neighbor])
                # print used for debugging
            else: print "parent is: %s, child is: %s, already colored: %s" 
                % (open_list[0], neighbor, colors[neighbor])
        open_list.pop(0)
    # now, return array of values that has one of the two colors
    zeros_array = []
    ones_array = []
    for key in colors.keys():
        if colors[key] == 0:
            zeros_array.append(key)
        else:
            ones_array.append(key)
    if len(set(zeros_array) & set(ones_array)) == 0:
        return zeros_array
    else:
        return None

这是我使用的图表:

{1: {2: 1, 4: 1}, 2: {1: 1, 3: 1, 5: 1}, 3: {8: 1, 2: 1}, 4: {1: 1}, 5: {2: 1, 6: 1}, 6: {5: 1}, 8: {3: 1}}

我把它画出来,图形可以可视化为一棵以 1 为根的树,并分支到节点 2 和 4,其中 4 是叶子,但 2 继续前进。我正在使用颜色计数器为相同颜色(0 或 1(的邻居着色。2 和 4 被赋予相同的颜色,然后算法正确地给出 3 和 5 与其父 2 相反的颜色,但是当返回一个级别来检查 4 时,颜色计数器会递增,所以当它达到 8 时,8 得到错误的颜色。

我被困在如何最好地解决这个问题上。

您应该

根据当前的顶点颜色选择颜色,例如colors[neighbor] = (colors[open_list[0]] + 1) % 2

此外,len(set(zeros_array) & set(ones_array)) == 0将始终true,因此您没有检查二分法是否进展顺利。你可以在if neighbor not in colors:的其他分支中检查它:只要断言你的邻居与当前顶点有不同的颜色。

最新更新