我正在尝试在DAG中实现循环检测,并且我使用字典通过在字典中将它们的值设置为True来跟踪递归堆栈中的顶点。一旦它们退出,我将它们的值设置为1。如果我遇到相同的节点,当它在递归堆栈中时,它是一个循环。 我将跳过与递归堆栈字典进行比较的代码部分。我尝试调试代码,但我似乎不明白它为什么不进入递归函数的比较部分。
PS:伙计们,这不是作业。我只是在练习。图表是:
directed_cyclic_graph = {
'g': ['h'],
'a': ['h', 'b'],
'b': ['c'],
'd': ['b', 'e'],
'c': ['f'],
'e': ['f'],
'i': ['i'],
'f': ['d'],
'h': [None]
}
代码:
def cycle_detection_recursive(adjList, vertex, parent, recursion_stack):
for nv in adjList[vertex]:
# In the case there is a cycle to itself
if recursion_stack[nv] and nv is not None:
print("Loop detected", nv, "-->", nv)
if nv not in parent:
if nv is not None:
parent[nv] = vertex
if not recursion_stack[nv]:
print(nv, "enters recursion stack")
recursion_stack[nv] = True
else:
print("Cycle detected:", "back edge", nv, "-->", vertex)
cycle_detection_recursive(adjList, nv, parent, recursion_stack)
recursion_stack[nv] = False
print(nv, "exits recursion stack")
def cycle_detection(DAG):
recursion_stack = {}
parent = {}
adjList = DAG
for vertex in adjList:
if vertex not in parent:
print(vertex, "enters recursion stack")
recursion_stack[vertex] = True
parent[vertex] = None
cycle_detection_recursive(adjList, vertex, parent, recursion_stack)
recursion_stack[vertex] = False
print(vertex, "exits recursion stack")
def main():
print("Breakpoint")
cycle_detection(directed_cyclic_graph)
最后,错误:
Traceback (most recent call last):
File "D:/Coding_Practice/Dynamic_Programming/graph_traversal.py", line 194, in <module>
b enters recursion stack
main()
File "D:/Coding_Practice/Dynamic_Programming/graph_traversal.py", line 190, in main
cycle_detection(directed_cyclic_graph)
File "D:/Coding_Practice/Dynamic_Programming/graph_traversal.py", line 177, in cycle_detection
cycle_detection_recursive(adjList, vertex, parent, recursion_stack)
File "D:/Coding_Practice/Dynamic_Programming/graph_traversal.py", line 146, in cycle_detection_recursive
if recursion_stack[nv] and nv is not None:
KeyError: 'c'