【问题标题】:Get disconnected pairs of nodes in the network graph?在网络图中获取断开的节点对?
【发布时间】:2019-04-11 14:57:08
【问题描述】:

这是我的数据集:

4095    546
3213    2059 
4897    2661 
...
3586    2583
3437    3317
3364    1216

每条线是一对节点,它们之间有一条边。整个数据集构建一个图。但我想获得许多彼此断开的节点对。如何从数据集中获得 1000 个(或更多)这样的节点对?如:

2761    2788
4777    3365
3631    3553
...
3717    4074
3013    2225

每一行都是一对没有边的节点。

【问题讨论】:

    标签: python-3.x matlab graph igraph social-networking


    【解决方案1】:

    请看EDIT下的部分!

    我认为其他选项更通用,从程序化的角度来看可能更好。我只是快速了解了如何使用 numpy 以非常简单的方式获取列表。

    首先创建邻接矩阵,你的节点列表是一个数组:

        import numpy as np
        node_list= np.random.randint(10 , size=(10, 2))
        A = np.zeros((np.max(node_list) + 1, np.max(node_list) + 1)) # + 1 to account for zero indexing
        A[node_list[:, 0],  node_list[:, 1]] = 1 # set connected nodes to 1
        x, y = np.where(A == 0) # Find disconnected nodes
        disconnected_list = np.vstack([x, y]).T # The final list of disconnected nodes
    

    不过,我不知道这将如何与真正的大规模网络一起工作。

    编辑:上面的解决方案是我想得太快了。截至目前,上述解决方案提供了节点之间的缺失边,而不是断开的节点(在有向图的情况下)。此外,disconnected_list 包含每个节点两次。这是解决方案的第二个想法:

        import numpy as np
        node_list= np.random.randint(10 , size=(10, 2))
        A = np.zeros((np.max(node_list) + 1, np.max(node_list) + 1)) # + 1 to account for zero indexing
        A[node_list[:, 0], node_list[:, 1]] = 1 # set connected nodes to 1 
        A[node_list[:, 1], node_list[:, 0]] = 1 # Make the graph symmetric
        A = A + np.triu(np.ones(A.shape)) # Add ones to the upper triangular
        # matrix, so they are not considered in np.where (set k if you want to consider the diagonal)
        x, y = np.where(A == 0) # Find disconnected nodes
        disconnected_list = np.vstack([x, y]).T # The final list of disconnected nodes
    

    【讨论】:

      【解决方案2】:

      只需执行 BFS 或 DFS 即可在 O(|E|) 时间内获取每个连接组件的大小。然后,一旦有了组件大小,您就可以轻松获得断开节点的数量:它是每对大小的乘积之和。

      例如。如果您的图有 3 个连通分量,大小分别为:50、20、100。那么断开节点对的数量为:50*20 + 50*100 + 20*100 = 8000

      如果您想实际输出断开连接的对而不是仅仅计算它们,您可能应该使用 union-find 然后遍历所有节点对并在它们不在同一个组件中时输出它们。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多