我在节点a和b之间遍历dfs,但是当我在节点b处中断循环时,算法仍在继续。这是我的代码:
import networkx as nx
def Graph():
G=nx.Graph()
k = 30
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(1,3)
for i in range(2,k+1):
G.add_edge(2*i-2,2*i)
G.add_edge(2*i-1,2*i)
G.add_edge(2*i-1,2*i+1)
G.add_edge(2*i,2*i+1)
G.add_nodes_from(G.nodes(), color='never coloured')
G.add_nodes_from(G.nodes(), label = -1)
G.add_nodes_from(G.nodes(), visited = 'no')
return G
def dfs(G,a,b,u):
global i
G.node[u]['visited'] = 'yes'
i += 1
G.node[u]['label'] = i
print(u)
print("i", i)
for v in G.neighbors(u):
if v == b:
G.node[v]['visited'] = 'yes'
i += 1
G.node[v]['label'] = i
print("b is ", v)
print("distance from a to b is ", G.node[v]['label'])
break### the problem area, doesn't break out the function
elif v != b:
if G.node[v]['visited'] == 'no':
dfs(G,a,b,v)
G=Graph()
a=1
b=19
i = 0
print('Depth-First-Search visited the following nodes of G in this order:')
dfs(G,a,b,a) ### count the DFS-path from a to b, starting at a
print('Depth-First Search found in G7 a path between vertices', a, 'and', b, 'of length:', G7.node[b]['label'])
print()我尝试过从for循环中返回,尝试使用中断,还尝试了try/catch方法。是否有任何优雅的方式来打破这个函数,或者我必须重写它,因为它不会通过u的所有邻居进行递归?
发布于 2016-02-26 12:10:52
这里的问题不是break或return,而是使用递归,而不是在每个递归调用中停止循环。您需要做的是从dfs函数返回一个结果,该结果告诉您是否找到了节点,如果递归调用找到了,则中断else块内的循环。就像这样:
def dfs(G,a,b,u):
global i
G.node[u]['visited'] = 'yes'
i += 1
G.node[u]['label'] = i
print(u)
print("i", i)
for v in G.neighbors(u):
if v == b:
G.node[v]['visited'] = 'yes'
i += 1
G.node[v]['label'] = i
print("b is ", v)
print("distance from a to b is ", G.node[v]['label'])
return True
elif v != b:
if G.node[v]['visited'] == 'no':
found = dfs(G,a,b,v)
if found:
return True
return False请注意,这如何将成功的结果传回到整个调用堆栈中。
发布于 2016-02-26 12:14:42
在这种情况下,我经常使用全局标志变量来表示搜索已经完成。例如,path_found。
发布于 2016-02-26 12:22:48
如果我理解得很好,你的问题不是你不能退出这个函数。
问题是你没有摆脱递归。有很多方法可以解决这个问题。
这是许多例子之一。通过返回True并在每个调用中检查这一点,您将开始冒泡并跳过递归过程中的每个循环。您可以将真值理解为“找到的路径”
def dfs(G,a,b,u):
global i
G.node[u]['visited'] = 'yes'
i += 1
G.node[u]['label'] = i
print(u)
print("i", i)
for v in G.neighbors(u):
if v == b:
G.node[v]['visited'] = 'yes'
i += 1
G.node[v]['label'] = i
print("b is ", v)
print("distance from a to b is ", G.node[v]['label'])
return True
elif v != b:
if G.node[v]['visited'] == 'no':
if dfs(G,a,b,v):
return Truehttps://stackoverflow.com/questions/35651147
复制相似问题