Skip to content

Python code snippet – How to convert adjacency matrix to adjacency list?

#Python:
def convert_to_adjacency(matrix):
    start = 0
    res = []
    lst = []
    n = len(matrix)

    for i in range(n):
        res.append(lst*n)
    while start < n:
        y = matrix[start]
        for i in range(len(y)):
            if y[i] == 1:
                res[start].append(i)
        start += 1
    return res
matrix = [[0, 1, 1, 1, 0, 1, 1, 0, 0],
          [1, 0, 0, 1, 0, 0, 1, 1, 0],
          [1, 0, 0, 1, 0, 0, 0, 0, 0],
          [1, 1, 1, 0, 1, 0, 0, 0, 0],
          [0, 0, 0, 1, 0, 1, 0, 0, 1],
          [1, 0, 0, 0, 1, 0, 0, 0, 1],
          [1, 1, 0, 0, 0, 0, 0, 0, 0],
          [0, 1, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 1, 1, 0, 0, 0]]
print(convert_to_adjacency(matrix))
See also  How to sort list in descending order in Python?
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.