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)
查找给定节点的n个邻居的最有效方法是使用深度优先搜索: http://en.wikipedia.org/wiki/Depth-first_search。下面的函数返回所有距离的start的邻域。但是,如果需要为所有节点查找n个邻居,那么对所有节点使用此函数并不是最有效的解决方案。相反,我们可以只对每个连接的组件中的一个开始节点使用这个函数,并计算其他节点相对于起始节点的n个邻居,但这将相当复杂。在
当您在图上执行宽度优先搜索时,从根节点r开始-节点被认为与r的距离在增加
因此,您只需要在执行BFS时跟踪节点的级别,请参见http://en.wikipedia.org/wiki/Level_structure以获得更深入的讨论。在
相关问题 更多 >
编程相关推荐