问题描述
我正在尝试在python中实现一个循环探测器。本质上,该算法应用BFS,并将每个节点标记为-1(未访问),0(正在工作)或1(已访问)。我的算法扫描邻居,如果邻居的状态为0,则检测到周期。
# this is a non-directed graph in nature
graph = {
'A': ['B','C'],'B': ['D','E'],'C': [],'D': ['B','E': ['B','D']
}
# 1 means visited 0 means in queue and -1 means not touched yet
status = {node: -1 for node in graph}
start = 'A'
queue = [start]
cycle = False
def traversal(graph):
start = queue.pop(-1)
for node in graph[start]:
if status[node] == -1:
queue.append(node)
status[node] = 0
if status[node] == 0:
cycle = True
if queue:
status[start] = 1
traversal(graph)
traversal(graph)
print(cycle)
我似乎找不到代码的问题。有人可以指出吗?
解决方法
在traversal
函数中,cycle
变量是局部变量。所以
cycle = True
将本地变量cycle
设置为True
,对全局 cycle
变量无效。
return
或您函数中的值
def traversal(graph):
cycle = False
... # the original function
return cycle
cycle = traversal(graph)
print(cycle)
或将cycle
变量标记为全局变量
cycle = False # global variable here
def traversal(graph):
global cycle
... # the original function
traversal(graph)
print(cycle)