我试图实现一个简单的邻接矩阵来跟踪哪些节点连接到无向图中的哪些节点。但是,我的邻接矩阵不断通过更改整个列而不是单个单元格来搞砸。这是我的代码:
def setup_adj_matrix(size, edges):
# initialize matrix with zeros
adj_matrix = [[0] * size] * size
# edges is a list of tuples, representing 2 nodes connected by an edge
for edge in edges:
v1 = edge[0]
v2 = edge[1]
adj_matrix[v1][v2] = 1
adj_matrix[v2][v1] = 1
for row in adj_matrix:
print row
对于具有 3 个节点 (0, 1, 2) 和边 [(0,1),(0,2),(1,2)] 的图,我应该得到
[[0,1,1],
[1,0,1],
[1,1,0]]
但是,我得到了全 1。问题可能出在哪里?