Professional Documents
Culture Documents
ipynb - Colaboratory
Reg No : URK20CS2065
Ex. No: 5
Date : 07/02/2021
Aim:
To write a program to get the shortest possible route that visits all the nodes exactly ones and
returns to the starting point, using dynamic programming approach.
Description:
Given a set of cities and distances between every pair of cities, the problem is to find the shortest
possible route that visits every city exactly once and returns to the starting point. .
Algorithm:
Function main():
Function tsp():
Program:
1
from itertools import permutations as perm
3
# implementation of traveling Salesman Problem
4
def tsp(dist, s):
5
path_dist=[] #to store the distances for different permutations
6
paths=[] # to store the paths for different permutations
7
vertex = [] #to store the vertices that are to be visited
8
for i in range(tot_c):
https://colab.research.google.com/drive/1Th7OyHj4nbnjxwaO1qi2Vkg6NmcJ55qo#scrollTo=nkVGD_0pZkQC 1/3
08/02/2022, 22:39 DAA EXP-5.ipynb - Colaboratory
9
if i != s:
10
vertex.append(i)
11
next_perm = perm(vertex) #computing different permuatations
12
for i in next_perm:
13
sum = 0
14
k = s
15
for j in i:
16
sum += dist[k][j]
17
k = j
18
sum += dist[k][s]
19
20
path_dist.append(sum)
21
paths.append(i)
22
23
min_dist=min(path_dist)
24
index=path_dist.index(min_dist)
25
print("\nThe shortest route: ")
26
print(s,end="-->")
27
for i in paths[index]:
28
print(i,end="-->")
29
print(s)
30
print("\nThe distance of the shortest route: ",min_dist)
31
32
if __name__=="__main__":
33
global tot_c
34
tot_c = int(input("Enter the number cities to be visited: "))
35
dist=[]
36
for i in range(tot_c):
37
dist.append(list(map(int,input("Enter distance between the cities: ").split())))
38
s = int(input("Enter the starting city: "))
39
tsp(dist, s)
40
# dist = [[0, 10, 15, 20],
41
# [5, 0, 9, 10],
42
# [6, 13, 0, 12],
43
# [8, 8, 9, 0]]
0-->1-->3-->2-->0
Result:
Thus the program to get the shortest route using dynamic programming has been written and
tested for various inputs.
https://colab.research.google.com/drive/1Th7OyHj4nbnjxwaO1qi2Vkg6NmcJ55qo#scrollTo=nkVGD_0pZkQC 2/3