如何在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))
答案 0 :(得分:3)
如果我理解正确,并且假设示例矩阵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)
答案 1 :(得分:2)
不确定为什么要定义visited
,就像double for循环一样,您要遍历所有元素一次。仍然与您正在执行的操作类似的简单方法是:
def edges(A):
edges = []
for i in range(len(A)):
for j in range(len(A[0])):
if (A[i][j] == 1):
edges.append((i,j))
return edges
print(edges(A))
[(0, 1), (0, 5), (1, 0), (1, 5), (2, 3), (2, 4), (3, 4), (5, 0)]
但是,您可以使用networkx
轻松地做到这一点。您可以使用from_numpy_matrix
从邻接矩阵创建图形,并使用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)
print(g.edges)
[(0, 1), (0, 5), (1, 5), (2, 3), (2, 4), (3, 4)]
答案 2 :(得分:1)
您可以将矩阵转换为邻接表,然后打印出节点和连接边:
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)]