我試圖實現一個簡單的鄰接矩陣來跟蹤哪些節點連接到無向圖中的哪些節點。然而,我的鄰接矩陣通過改變整個列而不是單個單元來保持擰緊。這是我的代碼:鄰接矩陣未正確填充python
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。任何想法可能出現問題?
http://docs.python.org/2/library/stdtypes.html# sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange - 該段落中的註釋2可以解決你的問題。 – ersran9