基于矩阵实现的Connected Components算法


1.连通分支

连通分支(Connected Component)是指:在一个图中,某个子图的任意两点有边连接,并且该子图去剩下的任何点都没有边相连。在 Wikipedia上的定义如下:
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.

Wikipedia上给的例子:


根据定义不难看出该图有三个连通分支。
另外,连通分支又分为弱连通分支和强连通分支。强连通分支是指子图点i可以连接到点j,同时点j也可以连接到点i。弱连通(只对有向图)分支是指子图点i可以连接到点j,但是点j可以连接不到点i。

2.传统算法

2.1算法思想

在传统算法中,我们是根据一点任意点,去找它的邻结点,然后再根据邻结点,找它的邻结点,直到所有的点遍历完。如下图:

图中有A、B、C、D和E五个点。我们先任选一个点C,然后找到C的邻结点E。然后我们再找E的邻结点,发现只有C,但是我们之前遍历过C,所以排除C。现在我们没有点可以遍历了,于是找到了第一个连通分支,如下蓝色标记:


接着,我们再从没有遍历的点(A、B、C)中任选一个点A。按照上述的方法,找到A的邻结点B。然后在找B的邻结点,找到A和D,但是A我们之前遍历过,所以排除A,只剩下了D。再找D的邻结点,找到B,同样B之前也遍历过了,所以也排除B,最后发现也没有点可以访问了。于是,就找到了第二个连通分支。到此图中所有的点已经遍历完了,因此该图有两个连通分支(A、B、D)和(C、E)。如下图:


2.2算法实现

下面是用Python实现的代码:
  1. class Data(object):  
  2.     def __init__(self, name):  
  3.         self.__name = name  
  4.         self.__links = set()  
  5.  
  6.     @property  
  7.     def name(self):  
  8.         return self.__name  
  9.   
  10.     @property  
  11.     def links(self):  
  12.         return set(self.__links)  
  13.   
  14.     def add_link(self, other):  
  15.         self.__links.add(other)  
  16.         other.__links.add(self)  
  17.       
  18. # The function to look for connected components.  
  19. def connected_components(nodes):  
  20.   
  21.     # List of connected components found. The order is random.  
  22.     result = []  
  23.   
  24.     # Make a copy of the set, so we can modify it.  
  25.     nodes = set(nodes)  
  26.   
  27.     # Iterate while we still have nodes to process.  
  28.     while nodes:  
  29.         # Get a random node and remove it from the global set.  
  30.         n = nodes.pop()  
  31.         print(n)  
  32.           
  33.         # This set will contain the next group of nodes connected to each other.  
  34.         group = {n}  
  35.   
  36.         # Build a queue with this node in it.  
  37.         queue = [n]  
  38.   
  39.         # Iterate the queue.  
  40.         # When it's empty, we finished visiting a group of connected nodes.  
  41.         while queue:  
  42.   
  43.             # Consume the next item from the queue.  
  44.             n = queue.pop(0)  
  45.   
  46.             # Fetch the neighbors.  
  47.             neighbors = n.links  
  48.   
  49.             # Remove the neighbors we already visited.  
  50.             neighbors.difference_update(group)  
  51.   
  52.             # Remove the remaining nodes from the global set.  
  53.             nodes.difference_update(neighbors)  
  54.   
  55.             # Add them to the group of connected nodes.  
  56.             group.update(neighbors)  
  57.   
  58.             # Add them to the queue, so we visit them in the next iterations.  
  59.             queue.extend(neighbors)  
  60.   
  61.         # Add the group to the list of groups.  
  62.         result.append(group)  
  63.   
  64.     # Return the list of groups.  
  65.     return result  
  66.       
  67. # The test code...  
  68. if __name__ == "__main__":  
  69.   
  70.     # The first group, let's make a tree.  
  71.     a = Data("a")  
  72.     b = Data("b")  
  73.     c = Data("c")  
  74.     d = Data("d")  
  75.     e = Data("e")  
  76.     f = Data("f")  
  77.     a.add_link(b)    #      a  
  78.     a.add_link(c)    #     / \  
  79.     b.add_link(d)    #    b   c  
  80.     c.add_link(e)    #   /   / \  
  81.     c.add_link(f)    #  d   e   f  
  82.   
  83.     # The second group, let's leave a single, isolated node.  
  84.     g = Data("g")  
  85.   
  86.     # The third group, let's make a cycle.  
  87.     h = Data("h")  
  88.     i = Data("i")  
  89.     j = Data("j")  
  90.     k = Data("k")  
  91.     h.add_link(i)    #    h————i  
  92.     i.add_link(j)    #    |    |  
  93.     j.add_link(k)    #    |    |  
  94.     k.add_link(h)    #    k————j  
  95.   
  96.     # Put all the nodes together in one big set.  
  97.     nodes = {a, b, c, d, e, f, g, h, i, j, k}  
  98.   
  99.     # Find all the connected components.  
  100.     number = 1  
  101.     for components in connected_components(nodes):  
  102.         names = sorted(node.name for node in components)  
  103.         names = ", ".join(names)  
  104.         print("Group #%i: %s" % (number, names))  
  105.         number += 1  
  106.   
  107.     # You should now see the following output:  
  108.     # Group #1: a, b, c, d, e, f  
  109.     # Group #2: g  
  110.     # Group #3: h, i, j, k  

3.基于矩阵的实现算法

3.1理论基础

1.邻接矩阵
邻接矩阵表示顶点之间相邻关系的矩阵,同时邻接矩阵分为有向邻接矩阵和无向邻接矩阵,如:

2.回路计算
假设有邻接矩阵,则回路计算公式为:

其中,表示从点i到点j经过k条路径形成的通路总数。当然,如果表示从点i到点j没有通路(有向图)或回路路(无向图)。


3.2算法推导

如果把经过0、1、2、3••••••条路径形成的回路矩阵求并集(注:经过0条路径形成的回路矩阵即为单位矩阵I),那么该并集C可以表示所有回路的总和,用公式可以表示为:
因此, 的(i,j)有非0值,表示点i和点j是同一个强连通的集合。
由于 比较复杂,但是,我们可以用下式计算:
C等于0的位置,D对应的位置也等于0;C等于1的位置,D对应的位置大于0。此时可以用D代替C进行计算。
对于D,这个式子几乎不收敛,因为我们需要修改它。现在让我们考虑式子 ,证明如下:


因此,

但是,现在还有一个问题,D并不总是收敛。因此,需要引入一个系数 ,使得用 代替A,则D重新定义为:

同理,由(证明同上),


可以求得:


其中,矩阵D中非0值所在列相同的行,属于同一个连通分支,即行结构相同的是一个连通分支。

3.3算法实现

下面是用Python实现的代码:
  1. from numpy.random import rand  
  2. import numpy as np  
  3.   
  4. #利用求并集和交集的方法  
  5. def cccomplex(adjacencyMat):  
  6.     def power(adjacencyMatPower, adjacencyMat):  
  7.         adjacencyMatPower *= adjacencyMat  
  8.         return adjacencyMatPower  
  9.     dimension = np.shape(adjacencyMat)[0]  
  10.     eye = np.mat(np.eye(dimension))  
  11.     adjacencyMat = np.mat(adjacencyMat)  
  12.     adjacencyMatPower = adjacencyMat.copy()  
  13.     result = np.logical_or(eye, adjacencyMat)  
  14.     for i in range(dimension):  
  15.         adjacencyMatPower = power(adjacencyMatPower, adjacencyMat)  
  16.         result = np.logical_or(result, adjacencyMatPower)  
  17.     final = np.logical_and(result, result.T)  
  18.     return final  
  19.   
  20. #利用求矩阵逆的方法      
  21. def connectedConponents(adjacencyMat, alpha = 0.5):  
  22.     n = np.shape(adjacencyMat)[0]  
  23.     E = np.eye(n)  
  24.     ccmatrix = np.mat(E - alpha * adjacencyMat)  
  25.       
  26.     return ccmatrix.I  
  27.   
  28. def init(dimension):  
  29.     mat = np.ones((dimension, dimension))  
  30.     mat[(rand(dimension) * dimension).astype(int), (rand(dimension) * dimension).astype(int)] = 0  
  31.     return mat  
  32.       
  33. if __name__ == "__main__":  
  34.     dimension = 4  
  35.     adjacencyMat = init(dimension)  
  36.     adjacencyMat1 = np.array([[0,1,0,0,0,0,0,0],                                                                                                    [0,0,1,0,1,1,0,0],     
  37.                               [0,0,0,1,0,0,1,0],  
  38.                               [0,0,1,0,0,0,0,1],  
  39.                               [1,0,0,0,0,1,0,0],  
  40.                               [0,0,0,0,0,0,1,0],      
  41.                               [0,0,0,0,0,1,0,1],  
  42.                               [0,0,0,0,0,0,0,1]])     
  43.     adjacencyMat2 = np.array([[0,1,1,0],[1,0,0,0],[1,0,0,0],[0,0,0,0]])  
  44.     print(cccomplex(adjacencyMat1))                 #(A, B, E) (C, D) (F, G) (H)  
  45.     print(connectedConponents(adjacencyMat2))     
  46.         #[[ True  True False False  True False False False]  
  47.         # [ True  True False False  True False False False]  
  48.         # [False False  True  True False False False False]  
  49.         # [False False  True  True False False False False]  
  50.         # [ True  True False False  True False False False]  
  51.         # [False False False False False  True  True False]  
  52.         # [False False False False False  True  True False]  
  53.         # [False False False False False False False  True]]  
  54.         #[[ 2.   1.   1.   0. ]  
  55.         # [ 1.   1.5  0.5  0. ]  
  56.         # [ 1.   0.5  1.5  0. ]  
  57.     # [ 0.   0.   0.   1. ]]  

4.评价

基于矩阵运算实现的图算法,有以下几点优势:
  1. 易于实现。利用矩阵可以仅仅通过矩阵与矩阵或矩阵与向量的运算就可以实现一些图算法。
  2. 易于并行。在超大矩阵运算中,可以采用分块的方式平行处理矩阵运算。同理,也可以很容易的移植分布式上(可以参考我的博文基于Spark实现的超大矩阵运算)。
  3. 效率更高。基于矩阵的图形算法更清晰突出的数据访问模式,可以很容易地优化(实验测试工作已完成)。
  4. 易于理解。这个需要对离散数学或者图论有一定基础,知道每一步矩阵运算所对应的物理意义或数学意义。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值