topological_sort.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. def topologicalSort(G,pos):
  4. zero_indeg_list = []
  5. sorted_list = []
  6. visited = [False]*len(G.nodes())
  7. while len(G.nodes())!=0:
  8. for node in G.nodes():
  9. if visited[node-1] == False:
  10. if G.in_degree(node) == 0:
  11. visited[node-1] = True
  12. zero_indeg_list.append(node)
  13. for node in zero_indeg_list:
  14. sorted_list.append(node)
  15. G.remove_node(node)
  16. zero_indeg_list.remove(node)
  17. return sorted_list
  18. #takes input from the file and creates a directed graph
  19. def CreateResultGraph(sorted_list):
  20. D = nx.DiGraph()
  21. for i in range(len(sorted_list)-1):
  22. D.add_edge(sorted_list[i], sorted_list[i+1])
  23. pos = nx.spring_layout(D)
  24. val_map = {}
  25. val_map[sorted_list[0]] = 'green'
  26. val_map[sorted_list[len(sorted_list)-1]] = 'red'
  27. values = [val_map.get(node, 'blue') for node in D.nodes()]
  28. nx.draw(D, pos, with_labels = True, node_color =values)
  29. #takes input from the file and creates a directed graph
  30. def CreateGraph():
  31. G = nx.DiGraph()
  32. f = open('input.txt')
  33. n = int(f.readline())
  34. for i in range(n):
  35. adj_list = map(int, (f.readline()).split())
  36. G.add_edge(adj_list[0], adj_list[1])
  37. return G
  38. #draws the graph
  39. def DrawGraph(G):
  40. pos = nx.spring_layout(G)
  41. nx.draw(G, pos, with_labels = True, node_color ='blue') #with_labels=true is to show the node number in the output graph
  42. return pos
  43. #main function
  44. if __name__== "__main__":
  45. G = CreateGraph()
  46. plt.figure(1)
  47. pos = DrawGraph(G)
  48. plt.figure(2)
  49. sorted_list = topologicalSort(G,pos)
  50. CreateResultGraph(sorted_list)
  51. plt.show()