我 dfs 在节点 a 和 b 之间遍历,但是当我在节点 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 循环,尝试使用 break 并尝试过 try/catch 方法。有没有什么优雅的方法可以打破这个函数,还是我必须重写它,因为它不会通过你的所有邻居递归?

最佳答案

这里的问题不是 breakreturn ,而是您使用递归并且没有在每个递归调用中停止循环。您需要做的是从您的 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

请注意这如何通过整个调用堆栈传播成功的结果。

关于python - 如何在Python中不返回或中断的情况下中断函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35651147/

10-15 09:40