Traveling Salesman algorithm using Dynamic Programming technique.

 Algorithm:

Algorithm TSP(distances)

{

 n:=length(distances);

 memo:=a 2D array of size n x (2^n) filled with None;

 dp(pos, visited)

 {

 if visited == (2^n) - 1 then

 return distances[pos][0], [0];

 if memo[pos][visited] is not None then

 return memo[pos][visited];

 shortest_dist := Infinity;

 shortest_path := [];

 for next_pos from 0 to n-1 do

 {

 if visited & (1 << next_pos) == 0 then

 {

 dist, path = dp(next_pos, visited | (1 << next_pos));

 dist := dist + distances[pos][next_pos];

 if dist < shortest_dist then

 {

 shortest_dist := dist;

shortest_path := [pos] + path;

 }

 }

 }

 memo[pos][visited] := (shortest_dist, shortest_path);

 return memo[pos][visited];

 }

 path := dp(0, 1);

 return path;

}


Source Code:

import sys

from typing import List, Tuple

def tsp(distances: List[List[int]]) -> Tuple[int, List[int]]:

 n = len(distances)

 memo = [[None] * (1 << n) for _ in range(n)]

 def dp(pos: int, visited: int) -> Tuple[int, List[int]]:

 if visited == (1 << n) - 1:

 return distances[pos][0], [0]

 if memo[pos][visited] is not None:

 return memo[pos][visited]

 shortest_dist, shortest_path = sys.maxsize, []

 for next_pos in range(n):

 if visited & (1 << next_pos) == 0:

 dist, path = dp(next_pos, visited | (1 << next_pos))

 dist += distances[pos][next_pos]

 if dist < shortest_dist:

shortest_dist = dist

shortest_path = [pos] + path

 memo[pos][visited] = (shortest_dist, shortest_path)

 return memo[pos][visited]

 _, path = dp(0, 1)

 return _, path

distances = [

 [0,3,2,0,3],

 [0,0,0,4,5],

 [0,0,0,5,4],

 [0,4,5,0,2],

 [3,5,4,2,0]

]

dist, path = tsp(distances)

print("Shortest distance:", dist)

print("Shortest path:", path)


Comments

Popular posts from this blog

2. Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.

Kruskal algorithm using greedy technique.