【发布时间】:2016-11-17 01:08:23
【问题描述】:
代码:
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 得到错误的颜色。
我不知道如何最好地解决这个问题。
【问题讨论】:
标签: python algorithm graph tree bipartite