Skip to content

Instantly share code, notes, and snippets.

@carloocchiena
Created November 4, 2022 09:15
Show Gist options
  • Save carloocchiena/1c43d0cd2d426d6ca37ed6327657b64d to your computer and use it in GitHub Desktop.
Save carloocchiena/1c43d0cd2d426d6ca37ed6327657b64d to your computer and use it in GitHub Desktop.
# TSP with heuristic dynamic programming
# Solution is based on "always picking the shortest route available" on the matrix
from itertools import permutations
def travel_salesman_problem(graph: list, path_sum: int = 0) -> int:
vertex = []
min_path = []
for i in range(len(graph)):
if i != path_sum:
vertex.append(i)
next_permutation = permutations(vertex)
for i in next_permutation:
current_pathweigth = 0
k = s
for j in i:
current_pathweigth += graph[k][j]
k = j
current_pathweigth += graph[k][s]
min_path.append(current_pathweigth)
x = sorted(min_path)
return x[0]
graph = [[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]]
path_sum = 0
travel_salesman_problem(graph, path_sum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment