0
我在圍繞我的代碼嵌套for循環包裝我的頭困難。我在wiki上按照Kahn的算法:Kahn's。我不明白如果outgoingEdge具有每個endArray元素(m)的傳入邊緣,如何測試。拓撲排序(卡恩算法)麻煩
這是我到目前爲止有:
def topOrdering(self, graph):
retList = []
candidates = set()
left = []
right = []
for key in graph:
left.append(key)
right.append(graph[key])
flattenedRight = [val for sublist in right for val in sublist]
for element in left:
if element not in flattenedRight:
#set of all nodes with no incoming edges
candidates.add(element)
candidates = sorted(candidates)
while len(candidates) != 0:
a = candidates.pop(0)
retList.append(a)
endArray = graph[a]
for outGoingEdge in endArray:
if outGoingEdge not in flattenedRight:
candidates.append(outGoingEdge)
#flattenedRight.remove(outGoingEdge)
del outGoingEdge
if not graph:
return "the input graph is not a DAG"
else:
return retList
啊,我忘了提,不允許空鍵。 –
@JeffreyPhung你是什麼意思,不允許空鍵? '3'不應該在鄰接列表中,因爲沒有外出邊緣? – niemmi
我給出的鄰接表沒有包含3個。所以從你的邏輯來看,會有一個異常錯誤,這就是我試圖按照自己的方式去做的原因。從你的方式,我想我將不得不再爲每個鄰居創建另一個鄰接表? –