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[0] 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?

enter image description here

1 Answers

0
Pipob Puthipiroj On Best Solutions

Took a while. It was tougher than I thought.

G = nx.grid_2d_graph(4, 5)
pos = dict( (n, n) for n in G.nodes() ) 

path = list(nx.dfs_edges(G, source = choice(list(G.nodes)))) # shows path

# create old_dict from an enumeration of the path
old_dict, new_dict = {v: k for v, k in enumerate([path[0][0]] + [i[1] for i in path] )}, {}

# invert old_dict to get new_dict, which returns order in the path of given node
for key, value in old_dict.items(): new_dict[value] = new_dict[value] + [key] if value in new_dict else [key]

# format new_dict into readable format
for key, value in new_dict.items(): new_dict[key] = value[0] if len(value) == 1 else tuple(value)


nx.draw(G, pos)
nx.draw(G, pos, edgelist = path, edge_color = 'r', width = 6, labels = new_dict)
plt.title('Using Depth-First Search')
plt.show()

Output