From be942e55e0a85815dd12057eee716b97ee2987b7 Mon Sep 17 00:00:00 2001 From: Jigar Joshi <49904152+JigarJoshi04@users.noreply.github.com> Date: Tue, 6 Oct 2020 00:31:25 +0530 Subject: [PATCH] travelling salesman problem algorithm added --- python/travelling_salesman_problem.py | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 python/travelling_salesman_problem.py diff --git a/python/travelling_salesman_problem.py b/python/travelling_salesman_problem.py new file mode 100644 index 0000000..25447c3 --- /dev/null +++ b/python/travelling_salesman_problem.py @@ -0,0 +1,44 @@ +# Python3 program to implement traveling salesman +# problem using naive approach. +from sys import maxsize +from itertools import permutations +V = 4 + +# implementation of traveling Salesman Problem +def travellingSalesmanProblem(graph, s): + + # store all vertex apart from source vertex + vertex = [] + for i in range(V): + if i != s: + vertex.append(i) + + # store minimum weight Hamiltonian Cycle + min_path = maxsize + next_permutation=permutations(vertex) + for i in next_permutation: + + # store current Path weight(cost) + current_pathweight = 0 + + # compute current path weight + k = s + for j in i: + current_pathweight += graph[k][j] + k = j + current_pathweight += graph[k][s] + + # update minimum + min_path = min(min_path, current_pathweight) + + return min_path + + +# Driver Code +if __name__ == "__main__": + + # matrix representation of graph + graph = [[0, 10, 15, 20], [10, 0, 35, 25], + [15, 35, 0, 30], [20, 25, 30, 0]] + s = 0 + print(travellingSalesmanProblem(graph, s))