简体   繁体   English

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

[英]How to Find Shortest Path Back to Self in a Graph/Adjacency Matrix - NetworkX

I've got a problem where I need to find a connected loop within an adjacency matrix.我有一个问题,我需要在邻接矩阵中找到一个连接的循环。 I'd like to find a loop that connects back to the original node over x hops.我想找到一个通过x跳连接回原始节点的循环。 shortest_path algorithms provided by NetworkX do not provide an option for a node to be the same source and target . NetworkX 提供的shortest_path算法没有为节点提供相同sourcetarget的选项。

For an example, this is the graph, and I'd like to find three colors with the largest distance between each other:例如,这是图表,我想找到three彼此之间距离最大的 colors:

在此处输入图像描述

This might be represented similar to:这可能表示为:

鄂尔多斯-仁义图

SOLUTIONS THAT DIDN'T WORK无效的解决方案

Modification of shortest path algorithm (route from a node to itself) 最短路径算法的修改(从一个节点到自身的路由)

There is a post here that mentions potentially setting weights or distances to infinite along the diagonal, but it doesn't appear networkx.all_shortest_paths , and any of the pathing algoirthms respect the self-loops as seen below:这里有一篇文章提到可能将weightsdistances沿对角线设置为无限,但它没有出现networkx.all_shortest_paths ,并且任何路径算法都尊重self-loops ,如下所示:

在此处输入图像描述

The only way I could figure out how to do this was using simple_cycles and then iterating through all cycles/loops to figure out what the distance might be:我能弄清楚如何做到这一点的唯一方法是使用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}")

Does someone have a better solution?有人有更好的解决方案吗?

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

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