K-th order neighbors in graph - Python networkx

Nik picture Nik · Aug 23, 2013 · Viewed 7.6k times · Source

I have a directed graph in which I want to efficiently find a list of all K-th order neighbors of a node. K-th order neighbors are defined as all nodes which can be reached from the node in question in exactly K hops.

I looked at networkx and the only function relevant was neighbors. However, this just returns the order 1 neighbors. For higher order, we need to iterate to determine the full set. I believe there should be a more efficient way of accessing K-th order neighbors in networkx.

Is there a function which efficiently returns the K-th order neighbors, without incrementally building the set?

EDIT: In case there exist other graph libraries in Python which might be useful here, please do mention those.

Answer

kelvin picture kelvin · Jan 9, 2014

You can use: nx.single_source_shortest_path_length(G, node, cutoff=K)

where G is your graph object.