[英]Is cycle in graph?
I have this structure 我有这个结构
class Node():
def __init__(self, name):
self.name=name
self.adjencyList=[]
self.visited = False
class Edge():
def __init__(self, inNode, outNode):
self.inNode=inNode
self.outNode=outNode
this lists: 列出:
nodes = []
edges = []
uniqueNodes = []
listOfVisitedNodes = []
And I want to check is in graph is cycle. 而且我要检查的是图中的周期。 I'm doing it with DFS alghoritm - if I visit node which is visited yet, in graph is cycle.
我正在使用DFS算法-如果我访问尚未访问的节点,则图中为循环。 There is my alghoritm:
有我的算法:
def DFS(node):
node.visited = True
listOfVisitedNodes.append(node)
uniqueNodes = listOfVisitedNodes
if len(set(uniqueNodes))==len(nodes):
return True
else:
for i in node.adjencyList:
if len(listOfVisitedNodes)==1:
if listOfVisitedNodes[-1] != i:
if i in listOfVisitedNodes:
return False
else:
DFS(i)
else:
if listOfVisitedNodes[-2] != i:
if i in listOfVisitedNodes:
return False
else:
DFS(i)
def isCycle():
if DFS(nodes[0]):
print 'there is no cycle'
else:
print 'there is cycle'
But I got still the same error - the alghoritm told me that in graph is allways cycle, doesnt matter what is the input. 但是我仍然遇到同样的错误-算法告诉我图形中的曲线始终循环,不管输入什么。 Thanks in advance for your your help guys.
在此先感谢您的帮助。
您忘记了返回递归的结果。
return DFS(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.