is it possible to use networkx dijkstra to avoid certain edges?

I am not aware of any inbuilt function that can do this. However, you can try the following steps to get the desired result:

  • Add a node attribute based on which you will filter the nodes while creating the Graph.

  • Filter the nodes and create a subgraph.

  • Call the Dijkstra function on the new subgraph

    import networkx 
    
    G = networkx.Graph()
    
    #Add an attribute color
    for i in range(5):
    
        if i==3:
            G.add_node(i, color='red')
        else:
            G.add_node(i, color='blue')
    
    # Add edges
    G.add_edge(0,1)
    G.add_edge(0,3)
    G.add_edge(1,2)
    G.add_edge(2,4)
    G.add_edge(3,4)
    
    # Functin to get filtered subgraph
    def get_filtered_graph(G, ignore_attribute, ignore_val):
        # Filter the nodes based on the node attribute and value
        # In this case it is red color
        filtered_nodes = [x for x,y in G.nodes(data=True)
                       if y[ignore_attribute]!=ignore_val]
    
        # Create the subgraph
        H = G.subgraph(filtered_nodes)
        return H
    
    ignore_attribute ='color'
    ignore_val = 'red'
    path = networkx.dijkstra_path(get_filtered_graph(G, filter_attribute, filter_val), 0, 4)
    
    print(path)
    # [0, 1, 2, 4]
    

References:

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top