The following code shows an example of graph traversal through networks in a grid graph.
# A “ladder graph” of length 5. import networkx as nx import matplotlib.pyplot as plt G = nx.grid_2d_graph(4, 5) pos = nx.spring_layout(G, iterations=100) # nx.draw(G, pos) # plt.show() nx.draw(G, pos, ) starting = choice(list(G.nodes)) # print("starting") path = list(nx.dfs_edges(g, source = starting)) # shows path # print(path) # j = [i for i in path] print(j) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos, edgelist=path, edge_color='r', width=6) plt.title('Using Depth-First Search') plt.show()
However, I feel like this would be much more useful if I could see which node the graph begun with as labels on the graph itself (e.g. 0, 1, 2, ....), and the exact sequence of nodes along the path. I understand that this might be a bit clunky for certain nodes which will be visited more than once.
Could someone help me with this?