繁体   English   中英

Python 函数:检查邻接矩阵中的连通性

[英]Python function: Check for connectivity in adjacency matrix

我在下面有一个邻接矩阵 D。 如果矩阵中的所有顶点都已连接,我如何编写一个返回 True 或 False 否则返回 True 的 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))

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

这是递归实现的 DFS 的伪代码(使用调用堆栈):

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),空间复杂度为 O(n)(对于vis数组)。

由于这是搜索“检查图的邻接矩阵的连通性”时出现的答案,让我们实际回答这个问题,而不是将其留在“这是一个很好理解的主题”。

只需使用NetworkX 的is_connected函数

假设您的邻接矩阵已经是 numpy 格式:

# An adjacency matrix is a square, binary matrix.
G = nx.from_numpy_matrix(adj_matrix)
if nx.is_connected(G):
    pass  # We're done! That easy.

如果您对连通组件更感兴趣,而不是整个图表, 请阅读此处

如果您需要输入不同格式的邻接矩阵,请尝试此处

使用图论的人也很感兴趣:图的代数连通性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM