NetworkX - path around a node
<p>I use <a href="http://networkx.readthedocs.io/en/latest/" rel="nofollow">NetworkX</a> to create the following graph.</p>

<p><a href="http://i.stack.imgur.com/C69Jr.png" rel="nofollow"><img src="http://i.stack.imgur.com/C69Jr.png" alt="Networkx graph"></a></p>

<p>The graph is created using:</p>

<pre><code>G = nx.grid_2d_graph(4,3)
</code></pre>

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

<p>Using the following code:</p>

<pre><code>G.neighbors((1, 1))
</code></pre>

<p>outputs:</p>

<pre><code>[(0, 1), (1, 2), (1, 0), (2, 1)]
</code></pre>

<p>What I need in addition are the points:</p>

<pre><code>[(0, 2), (2, 2), (2, 0), (0, 0)]
</code></pre>

<p>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.</p>

<p><strong>EDIT:</strong></p>

<p>After being inspired by @orestiss and fiddling around I came up with this.</p>

<pre><code>l = list()
center = (1, 1)
for neighb in G.neighbors(center):
    others = [n for n in G.neighbors(center) if n != neighb]
    for other in others:
        l.append([n for n in nx.common_neighbors(G, neighb, other) if n != center])
    l.append([neighb])
lf = list(set([item for sublist in l for item in sublist]))
</code></pre>

<p>With that I get all nodes which are in the cycle around <em>center</em>, except <em>center</em> itself.
This works also for boundary nodes.</p>

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

<p>the code would be : </p>

<pre><code>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]:
              in_loop.add(neighb)
              break

print in_loop
</code></pre>

python networkx