首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >求节点的n次邻域

求节点的n次邻域
EN

Stack Overflow用户
提问于 2014-03-30 10:15:46
回答 4查看 6.3K关注 0票数 9

我对networkx很陌生,实际上我对如何有效地找到节点的n度邻域感到有点困惑。节点v_i的n次邻域是与v_i完全不同的n个节点集合,给定一个指定的n个节点,需要为图/网络中的每个节点找到n次邻域。

假设我有下面的图,我想要找到节点v1的v1邻域。那将是v2和v3。接下来,假设我想找到节点v1的v1邻域,那就是v4。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-03-30 13:20:46

代码语言:javascript
运行
复制
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']
票数 10
EN

Stack Overflow用户

发布于 2014-03-30 12:28:10

查找给定节点的n个邻居的最有效方法是使用深度优先搜索:搜索。下面的函数返回所有距离的开始的邻居。但是,如果您需要为所有节点找到n个邻居,那么对所有节点使用这个函数并不是最有效的解决方案。相反,我们可以只对每个连接组件中的一个开始节点使用这个函数,并计算其他节点相对于启动节点的n个邻居,但这会非常复杂。

代码语言:javascript
运行
复制
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)    
票数 1
EN

Stack Overflow用户

发布于 2014-03-30 15:18:36

当您首先对图执行宽度搜索时,从根节点r开始--节点被认为是从r到r的不断增加的距离。

因此,您只需要在执行BFS时跟踪节点的级别,请参阅结构进行更深入的讨论。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22742754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档