コード:使用BFS
{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}}
が、私はそれを描いたグラフは次のように可視化することができます。
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とノード4に分岐します。ここで4はリーフですが、2は継続します。私は隣人に同じ色(0か1)を色付けするためにカラーカウンタを使用しています。 2と4に同じ色が与えられていれば、アルゴリズムは3と5に親の2の反対の色を正しく与えるが、1つのレベルをチェック4に戻すときにはカラーカウンタがインクリメントされるので、 8が間違った色になります。
この問題を解決するにはどうすればいいですか?あなたの現在の頂点の色に応じて色を選択する必要があります
あなたの行を:colors [neighbor] =(colors [open_list [0]] + 1)%2に変更しました。ありがとう! –
ええ、綴りが間違っています – mingaleg