在 python 的邻接矩阵中打印图形的所有边

printing all the edges of a graph in an adjacency matrix in python

如何在 python 中打印具有给定邻接矩阵的图的所有边?例如,如果 0 与 3 和 8 相邻,则应打印: 0 3 0 8 不重复 我一直在使用 Bfs,但我不知道如何更新队列和当前元素。

到目前为止,这是我的代码

A =  [[0, 1, 0, 0, 0, 1], 
      [1, 0, 0, 0, 0, 1], 
      [0, 0, 0, 1, 1, 0], 
      [0, 0, 0, 0, 1, 0],
      [0, 0, 0, 0, 0, 0],
      [1, 0, 0, 0, 0, 0]]

def edges(A):
    visited = [False] * len(A)
    queue = []

    s = [0][0]
    queue.append(s)
    visited[s] = True

    while len(queue) > 0:
        s = queue.pop(0)
        print(s)
        for i in range(len(A)):
            print(i)

            for j in range(len(A[0])):
                if A[i][j] == 1 and visited[s]== False:

                    queue.append([i][j])

                    visited[s] = True

print(edges(A))

如果我理解正确,并且鉴于您的示例矩阵 A 是不对称的,您可以这样做:

A =  [[0, 1, 0, 0, 0, 1],
      [1, 0, 0, 0, 0, 1],
      [0, 0, 0, 1, 1, 0],
      [0, 0, 0, 0, 1, 0],
      [0, 0, 0, 0, 0, 0],
      [1, 0, 0, 0, 0, 0]]

def edges(adj):

    for i, neighbors in enumerate(adj):
        for j, v in enumerate(neighbors):
            if v:
                yield (i, j)


for edge in edges(A):
    print(edge)

输出

(0, 1)
(0, 5)
(1, 0)
(1, 5)
(2, 3)
(2, 4)
(3, 4)
(5, 0)

一种简单的方法是遍历邻接矩阵,并构建一个元组列表,其中包含存在连接的索引:

[(i,j) for i,l in enumerate(A) for j,v in enumerate(l) if v]
# [(0, 1), (0, 5), (1, 0), (1, 5), (2, 3), (2, 4), (3, 4), (5, 0)]

但是,您可以使用 networkx 轻松地做到这一点。您可以使用 from_numpy_matrix, and print a list with the edges using edges:

从邻接矩阵创建图形
A =  np.array([[0, 1, 0, 0, 0, 1], 
               [1, 0, 0, 0, 0, 1], 
               [0, 0, 0, 1, 1, 0], 
               [0, 0, 0, 0, 1, 0],
               [0, 0, 0, 0, 0, 0],
               [1, 0, 0, 0, 0, 0]])

import networkx as nx
g = nx.from_numpy_matrix(A, create_using=nx.DiGraph)
g.edges()
# OutEdgeView([(0, 1), (0, 5), (1, 0), (1, 5), (2, 3), (2, 4), (3, 4), (5, 0)])

您可以将矩阵转换为邻接表,然后打印出节点和连接边:

A = [
    [0, 1, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 1],
    [0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 1, 0],
    [0, 0, 0, 0, 0, 0],
    [1, 0, 0, 0, 0, 0],
]


def matrix_to_list(matrix):
    """Convert adjacency matrix to adjacency list"""
    graph = {}
    for i, node in enumerate(matrix):
        adj = []
        for j, connected in enumerate(node):
            if connected:
                adj.append(j)
        graph[i] = adj
    return graph


adjacency_list = matrix_to_list(A)
print(adjacency_list)
# {0: [1, 5], 1: [0, 5], 2: [3, 4], 3: [4], 4: [], 5: [0]}


connected_edges = [
    (node, edge) for node, edges in adjacency_list.items() for edge in edges
]
print(connected_edges)
# [(0, 1), (0, 5), (1, 0), (1, 5), (2, 3), (2, 4), (3, 4), (5, 0)]