Skip to content

Instantly share code, notes, and snippets.

@seanbenhur
Created August 28, 2020 07:44
Show Gist options
  • Save seanbenhur/95ce4c4842e962bd39e1b5fed27b76a9 to your computer and use it in GitHub Desktop.
Save seanbenhur/95ce4c4842e962bd39e1b5fed27b76a9 to your computer and use it in GitHub Desktop.
routes = []
#write a function to find path
def find_path(node, cities, path, distance):
#add way point
path.append(node)
#calcualte path length
if len(path) > 1:
distance += cities[path[-2]][node]
#if path contains all cities and is not a dead end
#add path from the first city
if (len(cities) == len(path)) and (path[0] in cities[path[-1]]):
global routes
path.append(path[0])
distance += cities[path[-2]][path[0]]
routes.append([distance, path])
#fork paths for al possible cities not yet used
for city in cities:
if(city not in path) and (node in cities[city]):
find_path(city, dict(cities), list(path), distance)
if __name__ == '__main__':
cities = {
'RV': {'S': 195, 'UL': 86, 'M': 178, 'BA': 180, 'Z': 91},
'UL': {'RV': 86, 'S': 107, 'N': 171, 'M': 123},
'M': {'RV': 178, 'UL': 123, 'N': 170},
'S': {'RV': 195, 'UL': 107, 'N': 210, 'F': 210, 'MA': 135, 'KA': 64},
'N': {'S': 210, 'UL': 171, 'M': 170, 'MA': 230, 'F': 230},
'F': {'N': 230, 'S': 210, 'MA': 85},
'MA': {'F': 85, 'N': 230, 'S': 135, 'KA': 67},
'KA': {'MA': 67, 'S': 64, 'BA': 191},
'BA': {'KA': 191, 'RV': 180, 'Z': 85, 'BE': 91},
'BE': {'BA': 91, 'Z': 120},
'Z': {'BA': 120, 'BE': 85, 'RV': 91}
}
print('Start city:')
find_path('RV', cities, [], 0)
routes.sort()
if len(routes) != 0:
print('shortest route: %s' % routes[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment