Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created March 19, 2017 03:19
Show Gist options
  • Select an option

  • Save rupalbarman/c08fc00a676002f24d50c56d1204d8fb to your computer and use it in GitHub Desktop.

Select an option

Save rupalbarman/c08fc00a676002f24d50c56d1204d8fb to your computer and use it in GitHub Desktop.
Utility to convert adjacency matrix into adjacency list in python, for efficient BFS and DFS maybe
# get adjancy matrix
n= int(input()) #number of vertices
am=[]
for i in range(n):
am.append([int(x) for x in input().split()])
print(am) #show matrix
print()
#conver to adjancy list
al= {} #doesnt contain path from a node to itself.
for x, row in enumerate(am):
al[x+1]=[]
for i, v in enumerate(row):
if v== 1 and i!=x:
al[x+1].append(i+1)
print(al)
@TaimurAkmal
Copy link

Works well!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment