How to delete all related nodes in a directed graph using networkx?

前端 未结 2 2057
星月不相逢
星月不相逢 2021-02-09 14:53

I\'m not sure exactly sure what the correct terminology is for my question so I\'ll just explain what I want to do. I have a directed graph and after I delete a node I want all

2条回答
  •  执笔经年
    2021-02-09 15:38

    Let me provide you with the python networkX code that solves your task:

    import networkx as nx
    import matplotlib.pyplot as plt#for the purpose of drawing the graphs
    DG=nx.DiGraph()
    DG.add_edges_from([(3,8),(3,10),(5,11),(7,11),(7,8),(11,2),(11,9),(11,10),(8,9)])
    DG.remove_node(11)
    

    connected_components method surprisingly doesn't work on the directed graphs, so we turn the graph to undirected, find out not connected nodes and then delete them from the directed graph

    UG=DG.to_undirected()
    not_connected_nodes=[]
    for component in nx.connected_components(UG):
        if len(component)==1:#if it's not connected, there's only one node inside
            not_connected_nodes.append(component[0])
    for node in not_connected_nodes:
        DG.remove_node(node)#delete non-connected nodes
    

    If you want to see the result, add to the script the following two lines:

    nx.draw(DG)
    plt.show() 
    

提交回复
热议问题