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
Post a Comment