Example 1: how to convert adjacency matrix to adjacency list
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))
Example 2: how to convert adjacency list to adjacency matrix
def convert_to_matrix(graph):
matrix = []
for i in range(len(graph)):
matrix.append([0]*len(graph))
for j in graph[i]:
matrix[i][j] = 1
return matrix
lst = [[1,2,3,5,6],[0,3,6,7],[0,3],[0,1,2,4],[3,5,8],[0,4,8],[0,1],[1],[4,5]]
print(convert_to_matrix(lst))