Andy Andy - 1 year ago 102
Python Question

Networkx - path around a node

I use NetworkX to create the following graph.

Networkx graph

The graph is created using:

G = nx.grid_2d_graph(4,3)

After that two nodes are modified with respect to their positions (just to explain the figure, not necessary for the answer).

Using the following code:

G.neighbors((1, 1))


[(0, 1), (1, 2), (1, 0), (2, 1)]

What I need in addition are the points:

[(0, 2), (2, 2), (2, 0), (0, 0)]

This would make up a "loop" around (1, 1) containing all nodes in that "loop". Since I dont't know the correct naming in terms of graphs I have a hard time searching after what I'm looking for.

Answer Source

I believe that in this specific case would suffice to find which neighbours your neighbours have in common.

the code would be :

in_loop = set()
root = (1,1)

for neighb in G.neighbors(root):
    others = [n for n in G.neighbors((1,1)) if n != neighb]
    for other in others:
         if neighb in [x for x in G.neighbors(other) if x != root]:

print in_loop
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download