Created
September 18, 2020 07:34
-
-
Save jsparmani/40b44b45705903be69ea4862ea3c1473 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import maxsize | |
# Count of total vertices in graph | |
V = 4 | |
def travellingSalesmanProblem(graph, s): | |
vertex = [] | |
for i in range(V): | |
if i != s: | |
vertex.append(i) | |
min_path = maxsize | |
while True: | |
weight = 0 | |
current = s | |
for i in range(len(vertex)): | |
weight += graph[current][vertex[i]] | |
current = vertex[i] | |
weight += graph[current][s] | |
min_path = min(min_path, weight) | |
if not step(vertex): | |
break | |
return min_path | |
def step(vertex): | |
n = len(vertex) | |
i = n - 2 | |
while i >= 0 and vertex[i] >= vertex[i + 1]: | |
i -= 1 | |
if i == -1: | |
return False | |
j = i + 1 | |
while j < n and vertex[j] > vertex[i]: | |
j += 1 | |
j -= 1 | |
vertex[i], vertex[j] = vertex[j], vertex[i] | |
left = i + 1 | |
right = n - 1 | |
while left < right: | |
vertex[left], vertex[right] = vertex[right], vertex[left] | |
left += 1 | |
right -= 1 | |
return True | |
if __name__ == "__main__": | |
# Adjacency List | |
graph = [[0, 10, 15, 20], [10, 0, 35, 25], | |
[15, 35, 0, 30], [20, 25, 30, 0]] | |
s = int(input("Please enter the starting vertex: ")) | |
print(travellingSalesmanProblem(graph, s-1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment