【问题标题】:Python: NetworkX Finding shortest path which contains given list of nodesPython:NetworkX寻找包含给定节点列表的最短路径
【发布时间】:2014-11-11 19:08:40
【问题描述】:

我有一个图表

G=nx.Graph()

及其边缘

G.add_edge('a', 'b')
G.add_edge('a', 'e')
G.add_edge('b', 'c')
G.add_edge('c', 'd')
G.add_edge('d', 'e')
G.add_edge('e', 'g')
G.add_edge('g', 'f')
G.add_edge('g', 'h')
G.add_edge('g', 'k')
G.add_edge('h', 'j')
G.add_edge('h', 'i')

现在假设我想得到一条从节点“a”开始的最短路径,并且应该包含节点['d', 'k'] 所以输出应该是['a', 'b', 'c', 'd', 'e', 'g', 'k'] 有没有networkx函数可以给我这样的输出?

【问题讨论】:

    标签: python graph networkx


    【解决方案1】:

    我不知道只有返回包含多个节点的最短路径的库函数。

    如果查看起始节点和结束节点之间的每条路径的计算成本不是很高,我会将返回路径列表过滤为仅包含我正在寻找的节点的路径。

    # A lambda to check if the list of paths includes certain nodes
    only_containing_nodes = lambda x: 'd' in x and 'k' in x
    
    # If you want to find the shortest path which includes those nodes this
    # will get all the paths and then they can be filtered and ordered by
    # their length.
    all_simple_paths = nx.all_simple_paths(G, source='a', target='k')
    
    # If you only want shortest paths which include both nodes even if a
    # path includes the nodes and is not the shortest.
    all_shortest_paths = nx.all_shortest_paths(G, source='a', target='k')
    
    filter(only_containing_nodes, all_simple_paths)
    # >>> [['a', 'b', 'c', 'd', 'e', 'g', 'k']]
    
    filter(only_containing_nodes, all_shortest_paths)
    # >>> []
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      您可以使用shortest_path 获取所有最短路径,然后通过验证它是否为子列表来比较包含['d', 'k'] 的路径。

      pathList= [p for p in nx.shortest_path(G,source='a')] #Target not specified 
      l=['d', 'k']
      def isSubList(G,l):
          return all(True if x in G else False for x in l )
      
      res= [x for x in pathList if  isSubList(x,l)]
      

      【讨论】:

      • 我得到 TypeError: all_shortest_paths() 至少需要 3 个参数(给定 2 个)。 all_shortest_paths() 函数需要目标。
      • 真的!试试@shortest_path
      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2013-10-07
      相关资源
      最近更新 更多