English 中文(简体)
Design and Analysis of Algorithms

Selected Reading

Travelling Salesman Problem
  • 时间:2024-11-05

Travelpng Salesman Problem


Previous Page Next Page  

The travelpng salesman problem is a graph computational problem where the salesman needs to visit all cities (represented using nodes in a graph) in a pst just once and the distances (represented using edges in the graph) between all these cities are known. The solution that is needed to be found for this problem is the shortest possible route in which the salesman visits all the cities and returns to the origin city.

If you look at the graph below, considering that the salesman starts from the vertex ‘a’, they need to travel through all the remaining vertices b, c, d, e, f and get back to ‘a’ while making sure that the cost taken is minimum.

salesman_graph

There are various approaches to find the solution to the travelpng salesman problem: naïve approach, greedy approach, dynamic programming approach, etc. In this tutorial we will be learning about solving travelpng salesman problem using greedy approach.

Travelpng Salesperson Algorithm

As the definition for greedy approach states, we need to find the best optimal solution locally to figure out the global optimal solution. The inputs taken by the algorithm are the graph G {V, E}, where V is the set of vertices and E is the set of edges. The shortest path of graph G starting from one vertex returning to the same vertex is obtained as the output.

Algorithm

    Travelpng salesman problem takes a graph G {V, E} as an input and declare another graph as the output (say G’) which will record the path the salesman is going to take from one node to another.

    The algorithm begins by sorting all the edges in the input graph G from the least distance to the largest distance.

    The first edge selected is the edge with least distance, and one of the two vertices (say A and B) being the origin node (say A).

    Then among the adjacent edges of the node other than the origin node (B), find the least cost edge and add it onto the output graph.

    Continue the process with further nodes making sure there are no cycles in the output graph and the path reaches back to the origin node A.

    However, if the origin is mentioned in the given problem, then the solution must always start from that node only. Let us look at some example problems to understand this better.

Examples

Consider the following graph with six cities and the distances between them −

graph_six_cities

From the given graph, since the origin is already mentioned, the solution must always start from that node. Among the edges leading from A, A → B has the shortest distance.

graph a to b

Then, B → C has the shortest and only edge between, therefore it is included in the output graph.

graph_b_to_c

There’s only one edge between C → D, therefore it is added to the output graph.

graph_c_to_d

There’s two outward edges from D. Even though, D → B has lower distance than D → E, B is already visited once and it would form a cycle if added to the output graph. Therefore, D → E is added into the output graph.

graph d to e

There’s only one edge from e, that is E → F. Therefore, it is added into the output graph.

graph e to f

Again, even though F → C has lower distance than F → A, F → A is added into the output graph in order to avoid the cycle that would form and C is already visited once.

graph f to a

The shortest path that originates and ends at A is A → B → C → D → E → F → A

The cost of the path is: 16 + 21 + 12 + 15 + 16 + 34 = 114.

Even though, the cost of path could be decreased if it originates from other nodes but the question is not raised with respect to that.

Example

The complete implementation of Travelpng Salesman Problem using Greedy Approach is given below −


#include <stdio.h>
int tsp_g[10][10] = {
   {12, 30, 33, 10, 45},
   {56, 22, 9, 15, 18},
   {29, 13, 8, 5, 12},
   {33, 28, 16, 10, 3},
   {1, 4, 30, 24, 20}
};
int visited[10], n, cost = 0;

/* creating a function to generate the shortest path */
void travelpngsalesman(int c){
   int k, adj_vertex = 999;
   int min = 999;
   
   /* marking the vertices visited in an assigned array */
   visited[c] = 1;
   
   /* displaying the shortest path */
   printf("%d ", c + 1);
   
   /* checking the minimum cost edge in the graph */
   for(k = 0; k < n; k++) {
      if((tsp_g[c][k] != 0) && (visited[k] == 0)) {
         if(tsp_g[c][k] < min) {
            min = tsp_g[c][k];
         }
         adj_vertex = k;
      }
   }
   if(min != 999) {
      cost = cost + min;
   }
   if(adj_vertex == 999) {
      adj_vertex = 0;
      printf("%d", adj_vertex + 1);
      cost = cost + tsp_g[c][adj_vertex];
      return;
   }
   travelpngsalesman(adj_vertex);
}

/* main function */
int main(){
   int i, j;
   n = 5;
   for(i = 0; i < n; i++) {
      visited[i] = 0;
   }
   printf("

Shortest Path:	");
   travelpngsalesman(0);
   printf("

Minimum Cost: 	");
   printf("%d
", cost);
   return 0;
}

Output


Shortest Path:	1 5 4 3 2 1

Minimum Cost: 	99

#include <iostream>
using namespace std;
int tsp_g[10][10] = {{12, 30, 33, 10, 45},
{56, 22, 9, 15, 18},
{29, 13, 8, 5, 12},
{33, 28, 16, 10, 3},
{1, 4, 30, 24, 20}
};
int visited[10], n, cost = 0;

/* creating a function to generate the shortest path */
void travelpngsalesman(int c){
   int k, adj_vertex = 999;
   int min = 999;
   
   /* marking the vertices visited in an assigned array */
   visited[c] = 1;
   
   /* displaying the shortest path */
   cout<<c + 1<<" ";
   
   /* checking the minimum cost edge in the graph */
   for(k = 0; k < n; k++) {
      if((tsp_g[c][k] != 0) && (visited[k] == 0)) {
         if(tsp_g[c][k] < min) {
            min = tsp_g[c][k];
         }
      adj_vertex = k;
      }
   }
   if(min != 999) {
      cost = cost + min;
   }
   if(adj_vertex == 999) {
      adj_vertex = 0;
      cout<<adj_vertex + 1;
      cost = cost + tsp_g[c][adj_vertex];
      return;
   }
   travelpngsalesman(adj_vertex);
}

/* main function */
int main(){
   int i, j;
   n = 5;
   for(i = 0; i < n; i++) {
      visited[i] = 0;
   }
   cout<<endl;
   cout<<"Shortest Path: ";
   travelpngsalesman(0);
   cout<<endl;
   cout<<"Minimum Cost: ";
   cout<<cost;
   return 0;
}

Output


Shortest Path: 1 5 4 3 2 1
Minimum Cost: 99

import java.util.*;
pubpc class TSPGREEDY {
   pubpc static void main(String[] args) {
      int[][] tsp_g = {
         { -1, 10, 20, 30 },
         { 10, -1, 20, 25 },
         { 15, 30, -1, 10 },
         { 20, 15, 40, -1 }
      };
      int cost = 0;
      int count = 0;
      int j = 0, i = 0;
      int min = Integer.MAX_VALUE;
      List<Integer> visited = new ArrayList<>();

      // The problem starts from 0th index city
      visited.add(0);
      int[] path = new int[tsp_g.length];
      while (i < tsp_g.length && j < tsp_g[i].length) {
         if (count >= tsp_g[i].length - 1) {
            break;
         }

         // If the city is unvisited and has minimum cost, update the cost
         if (j != i && !(visited.contains(j))) {
            if (tsp_g[i][j] < min) {
               min = tsp_g[i][j];
               path[count] = j + 1;
            }
         }
         j++;

         // Check all paths from the
         // ith indexed city
         if (j == tsp_g[i].length) {
            cost += min;
            min = Integer.MAX_VALUE;
            visited.add(path[count] - 1);
            j = 0;
            i = path[count] - 1;
            count++;
         }
      }

      // Update the ending city in array
      // from city which was last visited
      i = path[count - 1] - 1;
      for (j = 0; j < tsp_g.length; j++) {
         if ((i != j) && tsp_g[i][j] < min) {
            min = tsp_g[i][j];
            path[count] = j + 1;
         }
      }
      cost += min;

      // Started from the node where
      // we finished as well.
      System.out.print("Minimum Cost is : ");
      System.out.println(cost);
   }
}

Output


Minimum Cost is : 55

from typing import DefaultDict
INT_MAX = 2147483647
tsp = [[-1, 10, 15, 20], [10, -1, 35, 25], [15, 35, -1, 30], [20, 25, 30, -1]]
sm = 0
counter = 0
j = 0
i = 0
mn = INT_MAX
visitedRouteList = DefaultDict(int)

visitedRouteList[0] = 1
route = [0] * len(tsp)
while i < len(tsp) and j < len(tsp[i]):
   if counter >= len(tsp[i]) - 1:
      break
   if j != i and (visitedRouteList[j] == 0):
      if tsp[i][j] < mn:
         mn = tsp[i][j]
         route[counter] = j + 1
   j += 1
   if j == len(tsp[i]):
      sm += mn
      mn = INT_MAX
      visitedRouteList[route[counter] - 1] = 1
      j = 0
      i = route[counter] - 1
      counter += 1

i = route[counter - 1] - 1
for j in range(len(tsp)):
   if (i != j) and tsp[i][j] < mn:
      mn = tsp[i][j]
      route[counter] = j + 1
sm += mn
print("Minimum Cost is :", sm)

Output


Minimum Cost is : 80
Advertisements