dfs_visual_4.py 1.1 KB

12345678910111213141516171819202122232425262728
  1. def DrawDFSPath(G, dfs_stk):
  2. pos = nx.spring_layout(G)
  3. nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
  4. edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
  5. nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
  6. for i in dfs_stk:
  7. #if there is more than one node in the dfs-forest, then print the corresponding edges
  8. if len(i) > 1:
  9. for j in i[ :(len(i)-1)]:
  10. if i[i.index(j)+1] in G[j]:
  11. nx.draw_networkx_edges(G, pos, edgelist = [(j,i[i.index(j)+1])], width = 2.5, alpha = 0.6, edge_color = 'r')
  12. else:
  13. #if in case the path was reversed because all the possible neighbours were visited, we need to find the adj node to it.
  14. for k in i[1::-1]:
  15. if k in G[j]:
  16. nx.draw_networkx_edges(G, pos, edgelist = [(j,k)], width = 2.5, alpha = 0.6, edge_color = 'r')
  17. break
  18. #main function
  19. if __name__ == "__main__":
  20. G, source = CreateGraph()
  21. dfs_stk = DFS(G, source)
  22. DrawDFSPath(G, dfs_stk)
  23. plt.show()