循环检测DFS程序用键退出

2024-06-30 16:42:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在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'

Tags: innoneifstacknotgraphparentvertex