I am doing this project and I'm having a problem with finding out which path has the shortest length. The setup is a supermarket. You start at the entrance and you get out at the cash deck. The points A,B,C,D are the points in the sections in the supermarket like the bake-off etc. At the input 'via' you can give the points which you want to pass.
#e = entrance
#k = cash desk
graph1 = {'e':{'a':1, 'b':5, 'c':6, 'd':6},
'a':{'e':2, 'b':4, 'c':5, 'd':5, 'k':7},
'b':{'e':5, 'a':5, 'c':3, 'd':5, 'k':6},
'c':{'e':6, 'a':5, 'b':3, 'd':4, 'k':5},
'd':{'e':6, 'a':3, 'b':5, 'c':4, 'k':2},
'k':{'a':7, 'b':6, 'c':5, 'd':2}
}
start = input('start')
end = input('end')
required = input('via').split(',')
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not start in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def exists_in_graph(graph, nodes):
for node in nodes:
if not node in graph:
return False
return True
allPaths = find_all_paths(graph1, start, end)
allPathsTroughNodes = list(filter(lambda x: exists_in_graph(x, required),
allPaths))
print(allPathsTroughNodes)
The output:
start e
end k
via a,c,d
[['e', 'a', 'b', 'c', 'd', 'k'], ['e', 'a', 'b', 'd', 'c', 'k'], ['e', 'a',
'c', 'b', 'd', 'k'], ['e', 'a', 'c', 'd', 'b', 'k'], ['e', 'a', 'c', 'd',
'k'], ['e', 'a', 'd', 'b', 'c', 'k'], ['e', 'a', 'd', 'c', 'b', 'k'], ['e',
'a', 'd', 'c', 'k'], ['e', 'b', 'a', 'c', 'd', 'k'], ['e', 'b', 'a', 'd',
'c', 'k'], ['e', 'b', 'c', 'a', 'd', 'k'], ['e', 'b', 'c', 'd', 'a', 'k'],
['e', 'b', 'd', 'a', 'c', 'k'], ['e', 'b', 'd', 'c', 'a', 'k'], ['e', 'c',
'a', 'b', 'd', 'k'], ['e', 'c', 'a', 'd', 'b', 'k'], ['e', 'c', 'a', 'd',
'k'], ['e', 'c', 'b', 'a', 'd', 'k'], ['e', 'c', 'b', 'd', 'a', 'k'], ['e',
'c', 'd', 'a', 'b', 'k'], ['e', 'c', 'd', 'a', 'k'], ['e', 'c', 'd', 'b',
'a', 'k'], ['e', 'd', 'a', 'b', 'c', 'k'], ['e', 'd', 'a', 'c', 'b', 'k'],
['e', 'd', 'a', 'c', 'k'], ['e', 'd', 'b', 'a', 'c', 'k'], ['e', 'd', 'b',
'c', 'a', 'k'], ['e', 'd', 'c', 'a', 'b', 'k'], ['e', 'd', 'c', 'a', 'k'],
['e', 'd', 'c', 'b', 'a', 'k']]
But I have no clue how I can calculate the length of each found path and how I can get the shortest one out of these.