代码:
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得到错误的颜色。
我坚持如何最好地解决这个问题。
答案 0 :(得分:0)
您应该根据当前的顶点颜色选择颜色,例如colors[neighbor] = (colors[open_list[0]] + 1) % 2
此外,len(set(zeros_array) & set(ones_array)) == 0
始终为true
,因此您无需检查二分法是否顺利。你可以在if neighbor not in colors:
的else分支中检查它:只是声明你的邻居有不同颜色的当前顶点。