【问题标题】:Python function: Check for connectivity in adjacency matrixPython函数:检查邻接矩阵中的连通性
【发布时间】:2017-10-10 05:30:55
【问题描述】:

我在下面有一个邻接矩阵 D。如何编写一个 python 函数,如果矩阵中的所有顶点都连接,则返回 True,否则返回 False?

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))

【问题讨论】:

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

标签: python vertex connectivity adjacency-matrix


【解决方案1】:

您可以使用 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 数组)。

【讨论】:

    【解决方案2】:

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

    只需使用NetworkX's is_connected function

    假设你的邻接矩阵已经是 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.
    

    如果您对连接组件更感兴趣,而不是整个图,read here

    如果您需要输入不同格式的邻接矩阵,try here

    使用图论的人也很感兴趣:the algebraic connectivity of a graph

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多