2017-10-10 213 views
-1

我有一个下面的邻接矩阵D.如何编写一个python函数,如果矩阵中的所有顶点都连接,则返回True;否则返回False?Python函数:检查邻接矩阵中的连通性

D = [['a', 'c', 'g', 'w', 'Q', 'f', 'Z', 't', 'R'], [0, 1, 2, 1, 9, 0, 0, 0, 0], [1, 0, 3, 4, 0, 0, 0, 0, 0], [2, 3, 0, 15, 2, 0, 0, 0, 0], [1, 4, 15, 0, 7, 0, 0, 0, 0], [9, 0, 2, 7, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 9, 0], [0, 0, 0, 0, 0, 2, 0, 0, 20], [0, 0, 0, 0, 0, 9, 0, 0, 0], [0, 0, 0, 0, 0, 0, 20, 0, 0]] 
 
def connectivity(adjMatrix): 
 
    connected = True 
 
    while connected == True: 
 
    # some algorithm that checks that each vertex can be connected to any other vertex 
 
    # if connected -> remains True 
 
    # if not connected -> False 
 
    return connected 
 
    
 
print(connectivity(D))

+1

这是一个很好理解的话题。您应该能够通过快速搜索轻松找到一个有效的算法。 –

回答

0

您可以使用DFS或深度优先搜索。你只需要在一个顶点上运行,因为如果一个顶点连接到所有的节点,这意味着图中有完整的连接。

这里为递归地执行DFS的伪代码(使用调用堆栈):用O(n)的空间复杂度

def DFS(vertex, adj, vis): 
    # adj is the adjacency matrix and vis is the visited nodes so far 
    set vertex as visited # example if vis is list: vis[vertex] = True 
    for vert in adj[vertex]: 
     if vert is not visited: 
      DFS(vertex, adj, vis) 
    return whether or not all vertices are visited # this only needs to happen 
                # for the first call 

该算法将具有O(n)的运行时(对于vis数组)。