代码之家  ›  专栏  ›  技术社区  ›  njho

如何在图/邻接矩阵中找到返回自身的最短路径-NetworkX

  •  0
  • njho  · 技术社区  · 4 年前

    我有一个问题,我需要在邻接矩阵中找到一个连接的循环。我想找到一个通过 x 啤酒花。 shortest_path NetworkX提供的算法不提供节点相同的选项 source target .

    举个例子,这是一张图,我想找出 three 彼此之间距离最大的颜色:

    enter image description here

    这可能类似于:

    erdos-renyi graph

    无效的解决方案

    Modification of shortest path algorithm (route from a node to itself)

    这里有一个帖子提到了潜在的设置 weights distances 沿对角线无限大,但它不会出现 networkx.all_shortest_paths self-loops 如下所示:

    enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   njho    4 年前

    我唯一能想到的方法就是使用 simple_cycles 然后迭代所有循环/循环,以确定距离可能是多少:

    cycles = [p for p in nx.simple_cycles(G)]
    
    num_nodes = 3
    for nodes in cycles: 
      if (len(nodes) != num_nodes): 
        continue
      print(nodes)
      total = 0
      node_pairs = list(walk_list(nodes,2,1))
    
      for pair in node_pairs: 
        if len(pair) == 2: 
          total += G[pair[0]][pair[1]]['weight']
        else: 
          total+= G[pair[0]][nodes[0]]['weight']
    
    
      print(f"Total Distance: {total}")
    
    

    有没有更好的解决方案?