I'm wondering what is an efficient way to covert an adjacency matrix to a dictionary representing connections between one node and another?
Example matrix:
matrix = [
[0,1,0,0,0,0],
[0,0,0,0,0,0],
[0,1,0,1,0,0],
[0,0,0,0,0,0],
[0,0,0,1,0,1],
[1,0,0,0,0,0]
]
Example output:
{0: [1], 1: [], 2: [1, 3], 3: [], 4: [3, 5], 5: [0]}
My code below actually generates the correct output; however, I believe it's very inefficient because I'm using two for loops. Is there any way I can optimize my code without using any libraries? Please let me know, and thank you!
def convertAdjMatrixtoDict(m):
graph = {}
for idx, row in enumerate(m):
res = []
for r in range(len(row)):
if row[r] != 0:
res.append(r)
graph[idx] = res
return graph