简体   繁体   English

基于边权重的2个节点之间的所有路径

[英]All Paths Between 2 Nodes on Basis of Edge Weight

I am new to programming and I am trying to find all possible paths between 2 nodes in which the sum of weight of edges is less than a given value. 我是编程的新手,我试图找到2个节点之间的所有可能路径,其中边的权重之和小于给定值。 I have implemented my graph in NetworkX and the nodes have no weight whatsoever. 我在NetworkX中实现了我的图形,节点没有任何重量。 Is there any predefined function in NetworkX I can use, or I need to write my own algorithm for same and if I do, what will be the best approach for same? 在我可以使用的NetworkX中是否有任何预定义的功能,或者我需要编写自己的算法,如果我这样做,那么最好的方法是什么?

Edit: The code right now is just reading input values and adding edges along with their respective weight through add_edge method defined in NetworkX. 编辑:现在的代码只是读取输入值,并通过NetworkX中定义的add_edge方法添加边缘及其各自的权重。 I am also trying to understand the code for all_simple_paths_graph method defined in NetworkX in order to modify it to keep a tab of weight but so far little headway, being new to Python. 我也试图理解在NetworkX中定义的all_simple_paths_graph方法的代码,以便修改它以保持重量的标签,但到目前为止还没有什么进展,对Python来说是新手。

Found an easy implementation for this by modifying an existing function of NetworkX. 通过修改NetworkX的现有功能,为此找到了一个简单的实现。 This function prints all paths between given nodes along which the sum of weight of edges is not more than given value. 此函数打印给定节点之间的所有路径,边缘权重之和不超过给定值。

def all_paths(G, source, target, w):
    cutoff = len(G)-1
    visited = [source]
    stack = [iter(G[source])]
    weight = 0
    while stack:
        children = stack[-1]
        child = next(children, None)
        if child is None:
            stack.pop()
            visited.pop()
        elif len(visited) < cutoff:
            if child == target:
                if (visited[-1],child) in G.nodes():
                    temp = G[visited[-1]][child]['weight']
                else:
                    temp = G[child][visited[-1]]['weight']
                if weight+temp <= w:
                    yield visited + [target]
            elif child not in visited:
                if (visited[-1],child) in G.nodes():
                    weight += G[visited[-1]][child]['weight']
                else:
                    weight += G[child][visited[-1]]['weight']
                visited.append(child)
                stack.append(iter(G[child]))
        else: 
            if child == target or target in children:
                if (visited[-1],child) in G.nodes():
                    temp = G[visited[-1]][child]['weight']
                else:
                    temp = G[child][visited[-1]]['weight']
                if weight+temp <= w:
                    yield visited + [target]
            stack.pop()
            visited.pop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM