这是我的数据集:
4095 546
3213 2059
4897 2661
...
3586 2583
3437 3317
3364 1216
每行是一对节点,它们之间有一条边。整个数据集构建一个图形。但是我想获得许多彼此断开的节点对。如何从数据集中获得1000个(或更多)这样的节点对?如:
2761 2788
4777 3365
3631 3553
...
3717 4074
3013 2225
每行是一对没有边的节点。
答案 0 :(得分:0)
只需执行BFS或DFS即可在O(|E|)
时间内获取每个已连接组件的大小。然后,一旦有了组件的大小,就可以轻松获得断开连接的节点数:这是每对大小的乘积之和。
例如。如果您的图具有3个连接的组件,其大小分别为:50、20、100。那么,断开连接的节点对数为:50*20 + 50*100 + 20*100 = 8000
。
如果您想实际输出断开连接的对,而不只是对它们进行计数,则可能应该使用并发查找,然后遍历所有对节点,如果它们不在同一组件中,则将它们输出。
答案 1 :(得分:0)
请参见“编辑”部分!
我认为其他选项更通用,从编程角度来看可能更好。我只是有个简单的主意,您如何使用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