简体   繁体   English

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

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

I have an adjacency matrix D below.我在下面有一个邻接矩阵 D。 How do I write up a python function that returns True if all the vertices in the matrix are connected or False if not?如果矩阵中的所有顶点都已连接,我如何编写一个返回 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))

You can use DFS or depth first search.您可以使用 DFS 或深度优先搜索。 You only need to run on one vertex, because if one vertex is connected to all the nodes, that means there is full connectivity within the graph.您只需要在一个顶点上运行,因为如果一个顶点连接到所有节点,则意味着图中存在完全连接。

Here is pseudocode for a recursively implemented DFS (using the call stack):这是递归实现的 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

This algorithm will have a runtime of O(n) with a space complexity of O(n) (for the vis array).该算法的运行时间为 O(n),空间复杂度为 O(n)(对于vis数组)。

Since this is the answer that turns up for searches of "check connectivity of graph's adjacency matrix", let's actually answer that instead of leaving it at "this is a well understood topic".由于这是搜索“检查图的邻接矩阵的连通性”时出现的答案,让我们实际回答这个问题,而不是将其留在“这是一个很好理解的主题”。

Just use NetworkX's is_connected function .只需使用NetworkX 的is_connected函数

Suppose your adjacency matrix is already in numpy format:假设您的邻接矩阵已经是 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.

If you were moreso interested in connected components, as opposed to the whole graph, read here .如果您对连通组件更感兴趣,而不是整个图表, 请阅读此处

If you needed to input your adjacency matrix from a different format, try here .如果您需要输入不同格式的邻接矩阵,请尝试此处

Also of interest for those who use graph theory: the algebraic connectivity of a graph .使用图论的人也很感兴趣:图的代数连通性

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

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