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个。所以从你的逻辑来看,会有一个异常错误,这就是我试图按照自己的方式去做的原因。从你的方式,我想我将不得不再为每个邻居创建另一个邻接表? –