I have a graph which we can think of is representing a network of train tracks. Each node is a station and each edge is a piece of track connecting two stations. Each station node may be connected by more than one track and all tracks are one way (i.e the graph is directed).
My job is to find as many routes as possible connecting one node with a set of destination nodes. Routes may contain cycles to the train track analogy breaks down here, but whatever. I have Python code to perform this task, but it is to slow so I would love to get some help in making it faster. Below is my traversal function:
from collections import deque
from itertools import product
def travel(graph, start, dests, count):
queue = deque([[(start, None)]])
paths = []
while queue:
path = queue.popleft()
at = path[-1][0]
if at in dests:
pp = [p[1] for p in path[1:]]
for real_path in product(*pp):
paths.append(''.join(real_path))
count -= 1
if count == 0:
return paths
adj = graph.get(at, {})
for item in adj.items():
queue.append(path + [item])
return paths
Called with a sample graph:
G = {
1 : {2 : 'mqr', 3 : 't'},
2 : {3 : 'q'},
3 : {1 : 'S', 4 : '_'},
4 : {3 : 't', 1 : 'xUI', 5 : '=+/'},
5 : {4 : 'q', 6 : '1'},
6 : {1 : '0'}
}
print(len(set(travel(G, 1, [6], 1000))))
1000 unique strings representing paths through the graph will be generated. Ideas on how to improve the travel
function would be greatly appreciated. Also on the format I'm using for representing the graph. It is usually very efficient to store a graph as a dict whose values are themselves dicts, but perhaps there is a better format.
t_=1
,qq_=1
occur, but notqqqqt_=1
. Going round and round cycles is allowed and a clever solution could definitely exploit that. However, I can't say whether cycle exploitation would be easy to implement or efficient. In the example..tStStStSt_=1
is such a cycle. \$\endgroup\$tSt_=1
,tStSt_=1
,tStStSt_=1
, …? I'm trying to get you to explain the constraints on the solution here: there's some choice about which routes to output, so in order to review your code, we need to know which outputs are acceptable and which are not. If asked to return 10 routes, will any 10 routes do? \$\endgroup\$