欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

networkx

程序员文章站 2024-03-15 21:21:24
...

输出某两点间所有simplepath路径(不带权重计算)

Generate all simple paths in the graph G from source to target.A simple path is a path with no repeated nodes

print(list(nx.all_simple_paths(g,'119.2355 25.95682', '119.23525 25.95688')))

有权图输出某两点间基于某种算法计算得出的路径路径(带某个权重计算)

shortpath=nx.dijkstra_path(g,'118.6513417 28.7636767', '118.6512676 28.763748',weight="")
print(shortpath)

遍历输出所有路径(有向图无向图都适用)

https://*.com/questions/55711945/networkx-getting-all-possible-paths-in-dag

  • 无向图遍历每个度为1的node

    roots = []
    leaves = []
    for node in g.nodes :
        if g.degree(node)==1:
            roots.append(node)
        # if g.in_degree(node) == 0 : # it's a root
        #     roots.append(node)
        # elif g.out_degree(node) == 0 : # it's a leaf
        #     leaves.append(node)
    
    #根据度为1的node,遍历所有路径
    for root in roots :
        for leaf in roots[roots.index(root):] :
            for path in nx.all_simple_paths(g, root, leaf) :
                print(path)
  • 有向图遍历
roots = []
leaves = []
for node in G.nodes :
  if G.in_degree(node) == 0 : # it's a root
    roots.append(node)
  elif G.out_degree(node) == 0 : # it's a leaf
    leaves.append(node)

for root in roots :
  for leaf in leaves :
    for path in nx.all_simple_paths(G, root, leaf) :
      print(path)

无向图输出图的连通子图的数量

   #无向图输出图的连通子图的数量
	print(nx.number_connected_components(g))
    #提取无向图中所有连通子图,返回一个列表
	lst=list(g.subgraph(c) for c in nx.connected_components(g))
    # print(nx.number_of_nodes(H))
    # print(nx.number_of_edges(H))
    # print(nx.average_shortest_path_length(H)) #计算平均最短路径长度
    # print(nx.degree_histogram(g))

    

    # path=nx.all_pairs_shortest_path(g)     #调用多源最短路径算法,计算图G所有节点间的最短路径
    # print(type(path))

    #计算最短路径长度
    # lenght=nx.floyd_warshall(g)
    # print(list(lenght))
    #计算最短路径上的前驱与路径长度
    # predecessor,distance1=nx.floyd_warshall_predecessor_and_distance(g)
    # print(predecessor)
    #计算两两节点之间的最短距离,并以numpy矩阵形式返回
    # distance2=nx.floyd_warshall_numpy(g)
相关标签: networkx

上一篇: networkx常用操作记录

下一篇: