How Do You Solve a Traveling Salesman Problem?

Different Approaches to Look Out For

Given a set of cities & the distance between every pair of cities as an adjacency matrix, find shortest route that visits each city once & returns to the starting point.

Explore examples for better understanding

Problem Statement

1. Choose any city as the starting and ending point.   2. Generate all possible permutations of cities that are (n-1)!.  3. Calculate the cost of each permutation.

Approach 1: Simple Approach

Check out further steps

Time complexity: O(N!), Where N is the number of cities.  Space complexity: O(1).

Want to see code implementation?

In this, subsets of required cities, distances between them & starting city are taken as inputs. Using recursive calls, the cost function for each subset is calculated.

Check out the blog to understand in detail

Approach 2: Dynamic Programming

Time Complexity: O(N^2*2^N)

Want to see code implementation?

1. Create a list to hold indices of cities & an array for results. 2. Traverse adjacency matrix & update cost if a cheaper path is found.  3. Generate minimum path cycle & return minimum cost.

Approach 3: Greedy Approach

Check out the blog to understand in detail

Time complexity: O(N^2*logN), Where N is the number of cities.  Space complexity: O(N).

Want to see code implementation?

Start your journey now and learn how to solve travelling salesman problem.

Ready to level up your coding skills?

Step Up Your Game with InterviewBit Web Stories

Don't miss out on the chance to upskill yourself with IntervewBit's engaging web stories.