fork download
  1. def topological(graph,start,path=[]):
  2. q = [start]
  3. while q:
  4. v = q.pop(0)
  5. if v not in path:
  6. path += [v]
  7. q = q + graph[v]
  8.  
  9. return path
  10.  
  11. graph = {
  12. 'a' : ['1','2','3','5'],#for 0 index
  13. '1' : ['4'],
  14. '2' : ['4'],
  15. '3' : ['4'],
  16. '4': ['6','8'],
  17. '5' : ['6'],
  18. '6' : ['7'],
  19.  
  20. '7' : ['9'],
  21. '8' : ['9'],
  22.  
  23. '9' : []
  24. }
  25. sort = (topological(graph, 'a'))
  26. print(sort)
  27.  
  28.  
Success #stdin #stdout 0.02s 9252KB
stdin
Standard input is empty
stdout
['a', '1', '2', '3', '5', '4', '6', '8', '7', '9']