我对networkx很陌生,实际上我对如何有效地找到节点的n度邻域感到有点困惑。节点v_i的n次邻域是与v_i完全不同的n个节点集合,给定一个指定的n个节点,需要为图/网络中的每个节点找到n次邻域。
假设我有下面的图,我想要找到节点v1的v1邻域。那将是v2和v3。接下来,假设我想找到节点v1的v1邻域,那就是v4。

发布于 2014-03-30 13:20:46
import networkx as nx
G = nx.Graph()
G.add_edges_from([('v1','v2'),('v2','v4'),('v1','v3')])
def neighborhood(G, node, n):
path_lengths = nx.single_source_dijkstra_path_length(G, node)
return [node for node, length in path_lengths.iteritems()
if length == n]
print(neighborhood(G, 'v1', 1))
# ['v2', 'v3']
print(neighborhood(G, 'v1', 2))
# ['v4']发布于 2014-03-30 12:28:10
查找给定节点的n个邻居的最有效方法是使用深度优先搜索:搜索。下面的函数返回所有距离的开始的邻居。但是,如果您需要为所有节点找到n个邻居,那么对所有节点使用这个函数并不是最有效的解决方案。相反,我们可以只对每个连接组件中的一个开始节点使用这个函数,并计算其他节点相对于启动节点的n个邻居,但这会非常复杂。
import networkx as nx
def n_neighbor(G, start):
# {distance : [list of nodes at that distance]}
distance_nodes = {}
# nodes at distance 1 from the currently visited ones
next_shell = G.neighbors(start)
# set of all visited nodes
visited=set()
visited.add(start)
# how fare we are from start
distance = 0
# until we run out of nodes
while len(next_shell) > 0:
# this will be the next shell
shell_after_this = []
# update distance
distance += 1
distance_nodes[distance] = []
# update visited and distance_nodes
for node in next_shell:
visited.add(node)
distance_nodes[distance].append(node)
# compute shell_after_this
for node in next_shell:
# add neighbors to shell_after_this
# if they have not been visited already
for neighbor in G.neighbors(node):
if neighbor not in visited:
shell_after_this.append(neighbor)
# we repeat with the new_shell
next_shell = set(shell_after_this)
return distance_nodes
# example
G=nx.Graph()
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,3)
G.add_edge(2,4)
G.add_edge(3,5)
G.add_edge(5,17)
G.add_edge(2,6)
print n_neighbor(G, 1) 发布于 2014-03-30 15:18:36
当您首先对图执行宽度搜索时,从根节点r开始--节点被认为是从r到r的不断增加的距离。
因此,您只需要在执行BFS时跟踪节点的级别,请参阅结构进行更深入的讨论。
https://stackoverflow.com/questions/22742754
复制相似问题