Skip to content

Instantly share code, notes, and snippets.

@MoralCode
Forked from westphahl/optimal_tsp.py
Last active May 7, 2019 17:33
Show Gist options
  • Select an option

  • Save MoralCode/15b893c738ea5eb96dee0d9d00d407d7 to your computer and use it in GitHub Desktop.

Select an option

Save MoralCode/15b893c738ea5eb96dee0d9d00d407d7 to your computer and use it in GitHub Desktop.
TSP brute-force solution in python3
"""
Author: Simon Westphahl <[email protected]>
Description: Brute-force implementation for solving the
travelling salesman problem.
"""
routes = []
def find_paths(node, cities, path, distance):
# Add way point
path.append(node)
# If path contains all cities, add path from
# last to first city and return.
if len(cities) == len(path):
global routes
path.append(path[0])
distance += cities[path[-2]][path[0]]
print path, distance
routes.append([distance, path])
return
# Calculate path length from current to last node
if len(path) > 1:
distance += cities[path[-2]][node]
# Fork paths for all cities not yet used
for city in cities:
if city not in path:
find_paths(city, dict(cities), list(path), distance)
if __name__ == '__main__':
cities = {
'RV': {
'UL': 36,
'A': 125,
'MM': 67
},
'UL': {
'RV': 36,
'A': 35,
'MM': 50
},
'A': {
'RV': 125,
'UL': 35,
'MM': 65
},
'MM': {
'RV': 67,
'UL': 50,
'A': 65
},
}
print "Start: RAVENSBURG"
find_paths('RV', cities, [], 0)
print "\n"
routes.sort()
print "Shortest route: %s" % routes[0]
@MoralCode
Copy link
Author

updated to python3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment