- Awards Season
- Big Stories
- Pop Culture
- Video Games
- Celebrities


How Has a Year Without Tourists Impacted the Overtourism Problem?

All press is good press — until that press goes too well. Although the Netherlands’ beautiful, canal-filled city of Amsterdam garners about $91.5 billion a year through tourism, the city and its residents feel more overwhelmed than grateful. In 2018, a whopping 18 million people visited Amsterdam, and experts estimate that number will climb to 42 million visitors by 2030. Longtime resident Ellen van Loon told CNN , “We [the Dutch] don’t want to turn into a Venice.”
Italy’s similarly canaled destination attracts 28 million visitors annually — while 2,000 residents abandon the city each year due to those same tourists. Of course, Amsterdam and Venice aren’t the only cities that have become synonymous with overtourism. In fact, hotspots all over the world, from beaches in Thailand to ancient sites in Peru, have simply attracted too many curious tourists. This phenomenon, known as overtourism, has led to environmental and ecological damage as well as a great deal of strain for locals who must navigate living amongst tourists and their economic impact.
Of course, the COVID-19 pandemic has stymied travel, shutting down airports, cities, borders and entire nations. According to the U.S. Travel Association , travel spending declined by an unheard of 42% in 2020; international and business travel suffered the most, with spending falling 76% and 70%, respectively. So, after a year of virtually no tourism, how are these (normally too heavily traveled) places, and the people that call them home, faring?
How Overtourism Impacts Some of the World’s Most Beautiful Destinations
Be it an ancient site, a crowded city or a place of natural splendor, popular destinations all feel the effects of overtourism differently. For example, Rapa Nui — often known to westerners as Easter Island — faces preservation issues, especially when it comes to the island’s famed moai sculptures. Meanwhile, the Galápagos Islands, the fragile and isolated ecosystem Charles Darwin popularized, has put a cap on how many visitors can travel to the archipelago each year. And in hotspot cities like Barcelona, Spain, locals are so furious with the unprecedented jump in tourists that they’ve coined a term to describe what overtourism is doing to the city: parquetematización — or the act of becoming a theme park.

Some of the other most heavily impacted destinations include:
- Santorini, Greece: Greece as a whole may be on the brink of an overtourism crisis. In 2018, the country hosted an unprecedented 32 million visitors, whereas back in 2010, that figure was closer to 15 million. The Greek National Tourism Organisation says it plans to strategically extend what is considered the summer holiday period so the influx of tourists doesn’t “[move] beyond the carrying capacity of the environment.” Of all locales, the small island of Santorini has been hit hardest, garnering a whopping 5.5 million annual visitors.
- Machu Picchu: Peru’s most well-known Inca citadel is one of those destinations everyone puts on their bucket list. Unfortunately, this wonder of the ancient world wasn’t built to sustain the more than 1.2 million tourists that trek to the archeological site annually. Since Peru can’t just close its most popular tourist spot, a new ticketing system was implemented in 2017 to promote preservation.
- Koh Tachai, Thailand: Like most Thai marine parks, Koh Tachai, an island in Similan National Park, is closed every May through October for the monsoon season. But in 2016, the park didn’t reopen. The beautiful beaches had been overrun with 14 times the number of people experts said the beaches should hold. Officials decided to close the island for rehabilitation, although many fear the damage is irreparable. In addition to problems related to general overcrowding, inexperienced divers — who were more concerned with photographs than their surroundings — damaged the island’s fragile reefs. As of 2019, Koh Tachai is closed to tourists indefinitely.
- Dubrovnik, Croatia: Although it joined UNESCO’s list of World Heritage Sites back in 1979, Dubrovnik only recently emerged as one of the Mediterranean’s top tourist destinations. Unfortunately, locals claim the Old City’s historic cathedrals, fortresses and buildings have swelled with Disneyland-level crowds — due to the popularity of HBO’s Game of Thrones and the sheer number of cruises it brings in.
- Boracay, Philippines: Boracay is known for having some of the most beautiful beaches in the world. But those beaches were closed to tourists in 2018 by the president of the Philippines. An estimated 1.7 million travelers visited the island within a 10-month period, raising major infrastructure concerns — namely in terms of sewage treatment.
How Has a Year Without Tourists Impacted These Normally Heavily Trafficked Places?
Cruises were one of the first aspects of the travel industry to shut down in 2020. In fact, the Centers for Disease Control and Prevention (CDC) found that between February 3 and March 13 roughly 200 COVID-19 cases in the U.S. were linked to cruise ship passengers. Soon enough, halts on air travel and widespread lockdowns followed.

In Venice, a city that’s usually visited by upwards of 32,000 cruise ship passengers a day, the pandemic has completely changed the day-to-day energy of life there. “Everyday life is a lot more pleasant without the congestion created by the crowds of tourists that came in large groups,” Venice resident Jane da Mosto told CNN Travel .
Of course, that calmer way of life comes at a cost financially. The reprieve from tourists has had that same dual impact the world over. Now, in light of the pandemic, only 75 people are allowed in Machu Picchu at a time, which translates to just under 700 visitors a day. That’s hundreds less than the norm — and, while it’s better for the ancient site, the financial impact will certainly be felt. While experts predict that the travel industry will bounce back, COVID-19 has definitely upset the industry’s stability — largely because the pandemic, and various countries’ reactions to it, are so unpredictable.
Still, some see the pandemic as a disruption to a vicious, seemingly unbreakable cycle. With overtourism, governments often make tradeoffs to keep the cash flowing in, only to scramble for solutions to restore environments and structures or appease upset locals. With this in mind, World Politics Review brings up an interesting question: “Should business-as-usual be salvaged at any cost, or is now the chance to create a smaller, slower and more sustainable model of global tourism?” While the COVID-19 pandemic may have only put a temporary pause on tourism, the pause itself could be a chance to recalibrate, to figure out a way to end overtourism once and for all.
MORE FROM ASK.COM

- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Divide & Conquer
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Optimal Substructure Property in Dynamic Programming | DP-2
- Overlapping Subproblems Property in Dynamic Programming | DP-1
- How to solve a Dynamic Programming Problem ?
- Tabulation vs Memoization
- Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique cap to every person)
- Digit DP | Introduction
- Ugly Numbers
- Program for nth Catalan Number
- Bell Numbers (Number of ways to Partition a Set)
- Coin Change | DP-7
- Subset Sum Problem | DP-25
- Subset Sum Problem in O(sum) space
- Introduction and Dynamic Programming solution to compute nCr%p
- Cutting a Rod | DP-13
- Painting Fence Algorithm
- Longest Common Subsequence | DP-4
- Count all subsequences having product less than K
- Maximum sum in a 2 x n grid such that no two elements are adjacent
- Min Cost Path | DP-6
- Longest Common Substring | DP-29
- Count ways to reach the nth stair using step 1, 2 or 3
- Count Balanced Binary Trees of Height h
- Floyd Warshall Algorithm | DP-16
- 0/1 Knapsack Problem
- Egg Dropping Puzzle | DP-11
- Box Stacking Problem | DP-22
- Partition problem | DP-18
Travelling Salesman Problem using Dynamic Programming
- Longest Palindromic Subsequence | DP-12
- Longest alternating subsequence
- Find all distinct subset (or subsequence) sums of an array
- Weighted Job Scheduling
- Number of paths with exactly k coins
- Count number of ways to jump to reach end
- Count number of ways to partition a set into k subsets
- Maximum subarray sum in O(n) using prefix sum
- Maximum number of trailing zeros in the product of the subsets of size k
- Minimum number of deletions to make a string palindrome
- Find if string is K-Palindrome or not | Set 1
- Find the longest path in a matrix with given constraints
- Find minimum sum such that one of every three consecutive elements is taken
- Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space
- Dynamic Programming | Building Bridges
- Palindrome Partitioning | DP-17
- Mobile Numeric Keypad Problem
- Longest Common Subsequence with at most k changes allowed
- The painter’s partition problem
- Matrix Chain Multiplication | DP-8
- Largest rectangular sub-matrix whose sum is 0
- Maximum profit by buying and selling a share at most k times
- Introduction to Dynamic Programming on Trees
- Traversal of tree with k jumps allowed between nodes of same height
- Difficulty Level : Hard
- Last Updated : 06 Feb, 2023
- Discuss(50+)
Travelling Salesman Problem (TSP):
Given a set of cities and the distance 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. Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle.
For example, consider the graph shown in the figure on the right side. A TSP tour in the graph is 1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80. The problem is a famous NP-hard problem. There is no polynomial-time know solution for this problem. The following are different solutions for the traveling salesman problem.
Naive Solution:
1) Consider city 1 as the starting and ending point.
2) Generate all (n-1)! Permutations of cities.
3) Calculate the cost of every permutation and keep track of the minimum cost permutation.
4) Return the permutation with minimum cost.
Time Complexity: Θ(n!)
Dynamic Programming:
Let the given set of vertices be {1, 2, 3, 4,….n}. Let us consider 1 as starting and ending point of output. For every other vertex I (other than 1), we find the minimum cost path with 1 as the starting point, I as the ending point, and all vertices appearing exactly once. Let the cost of this path cost (i), and the cost of the corresponding Cycle would cost (i) + dist(i, 1) where dist(i, 1) is the distance from I to 1. Finally, we return the minimum of all [cost(i) + dist(i, 1)] values. This looks simple so far.
Now the question is how to get cost(i)? To calculate the cost(i) using Dynamic Programming, we need to have some recursive relation in terms of sub-problems.
Let us define a term C(S, i) be the cost of the minimum cost path visiting each vertex in set S exactly once, starting at 1 and ending at i . We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset, then we calculate C(S, i) for all subsets S of size 3 and so on. Note that 1 must be present in every subset.
Below is the dynamic programming solution for the problem using top down recursive+memoized approach:-
For maintaining the subsets we can use the bitmasks to represent the remaining nodes in our subset. Since bits are faster to operate and there are only few nodes in graph, bitmasks is better to use.
For example: –
10100 represents node 2 and node 4 are left in set to be processed
010010 represents node 1 and 4 are left in subset.
NOTE:- ignore the 0th bit since our graph is 1-based
Time Complexity : O(n 2 *2 n )
Auxiliary Space : O(n 2 ) , where n is number of Nodes/Cities here.
For a set of size n, we consider n-2 subsets each of size n-1 such that all subsets don’t have nth in them. Using the above recurrence relation, we can write a dynamic programming-based solution. There are at most O(n*2 n ) subproblems, and each one takes linear time to solve. The total running time is therefore O(n 2 *2 n ). The time complexity is much less than O(n!) but still exponential. The space required is also exponential. So this approach is also infeasible even for a slightly higher number of vertices. We will soon be discussing approximate algorithms for the traveling salesman problem.
Next Article: Traveling Salesman Problem | Set 2
References:
http://www.lsi.upc.edu/~mjserna/docencia/algofib/P07/dynprog.pdf
http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Solve DSA problems on GfG Practice.
Please Login to comment...
- akashcherukuri007
- serjeelranjan
- tapeshdua420
- lokeshpotta20
- sagartomar9927
- akshaytripathi19410
Prepare for Microsoft & other Product Based Companies
In JAVA/C++ Language
Improve your Coding Skills with Practice
Start your coding journey now.

Travelling Salesman Problem: Python, C++ Algorithm
What is the travelling salesman problem (tsp).
Travelling Salesman Problem (TSP) is a classic combinatorics problem of theoretical computer science. The problem asks to find the shortest path in a graph with the condition of visiting all the nodes only one time and returning to the origin city.
The problem statement gives a list of cities along with the distances between each city.
Objective: To start from the origin city, visit other cities only once, and return to the original city again. Our target is to find the shortest possible path to complete the round-trip route.
Example of TSP
Here a graph is given where 1, 2, 3, and 4 represent the cities, and the weight associated with every edge represents the distance between those cities.

The goal is to find the shortest possible path for the tour that starts from the origin city, traverses the graph while only visiting the other cities or nodes once, and returns to the origin city.
For the above graph, the optimal route is to follow the minimum cost path: 1-2-4-3-1. And this shortest route would cost 10+25+30+15 =80
Different Solutions to Travelling Salesman Problem

Travelling Salesman Problem (TSP) is classified as a NP-hard problem due to having no polynomial time algorithm. The complexity increases exponentially by increasing the number of cities.
There are multiple ways to solve the traveling salesman problem (tsp). Some popular solutions are:
The brute force approach is the naive method for solving traveling salesman problems. In this approach, we first calculate all possible paths and then compare them. The number of paths in a graph consisting of n cities is n! It is computationally very expensive to solve the traveling salesman problem in this brute force approach.
The branch-and-bound method: The problem is broken down into sub-problems in this approach. The solution of those individual sub-problems would provide an optimal solution.
This tutorial will demonstrate a dynamic programming approach, the recursive version of this branch-and-bound method, to solve the traveling salesman problem.
Dynamic programming is such a method for seeking optimal solutions by analyzing all possible routes. It is one of the exact solution methods that solve traveling salesman problems through relatively higher cost than the greedy methods that provide a near-optimal solution.
The computational complexity of this approach is O(N^2 * 2^N) which is discussed later in this article.
The nearest neighbor method is a heuristic-based greedy approach where we choose the nearest neighbor node. This approach is computationally less expensive than the dynamic approach. But it does not provide the guarantee of an optimal solution. This method is used for near-optimal solutions.
Algorithm for Traveling Salesman Problem
We will use the dynamic programming approach to solve the Travelling Salesman Problem (TSP).
Before starting the algorithm, let’s get acquainted with some terminologies:
- A graph G=(V, E), which is a set of vertices and edges.
- V is the set of vertices.
- E is the set of edges.
- Vertices are connected through edges.
- Dist(i,j) denotes the non-negative distance between two vertices, i and j.
Let’s assume S is the subset of cities and belongs to {1, 2, 3, …, n} where 1, 2, 3…n are the cities and i, j are two cities in that subset. Now cost(i, S, j) is defined in such a way as the length of the shortest path visiting node in S, which is exactly once having the starting and ending point as i and j respectively.
For example, cost (1, {2, 3, 4}, 1) denotes the length of the shortest path where:
- Starting city is 1
- Cities 2, 3, and 4 are visited only once
- The ending point is 1
The dynamic programming algorithm would be:
- Set cost(i, , i) = 0, which means we start and end at i, and the cost is 0.
- When |S| > 1, we define cost(i, S, 1) = ∝ where i !=1 . Because initially, we do not know the exact cost to reach city i to city 1 through other cities.
- Now, we need to start at 1 and complete the tour. We need to select the next city in such a way-
cost(i, S, j)=min cost (i, S−{i}, j)+dist(i,j) where i∈S and i≠j
For the given figure, the adjacency matrix would be the following:

Let’s see how our algorithm works:
Step 1) We are considering our journey starting at city 1, visit other cities once and return to city 1.
Step 2) S is the subset of cities. According to our algorithm, for all |S| > 1, we will set the distance cost(i, S, 1) = ∝. Here cost(i, S, j) means we are starting at city i, visiting the cities of S once, and now we are at city j. We set this path cost as infinity because we do not know the distance yet. So the values will be the following:
Cost (2, {3, 4}, 1) = ∝ ; the notation denotes we are starting at city 2, going through cities 3, 4, and reaching 1. And the path cost is infinity. Similarly-
cost(3, {2, 4}, 1) = ∝
cost(4, {2, 3}, 1) = ∝
Step 3) Now, for all subsets of S, we need to find the following:
cost(i, S, j)=min cost (i, S−{i}, j)+dist(i,j), where j∈S and i≠j
That means the minimum cost path for starting at i, going through the subset of cities once, and returning to city j. Considering that the journey starts at city 1, the optimal path cost would be= cost(1, {other cities}, 1).
Let’s find out how we could achieve that:
Now S = {1, 2, 3, 4}. There are four elements. Hence the number of subsets will be 2^4 or 16. Those subsets are-
1) |S| = Null:
2) |S| = 1:
{{1}, {2}, {3}, {4}}
3) |S| = 2:
{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}
4) |S| = 3:
{{1, 2, 3}, {1, 2, 4}, {2, 3, 4}, {1, 3, 4}}
5) |S| = 4:
{{1, 2, 3, 4}}
As we are starting at 1, we could discard the subsets containing city 1.
The algorithm calculation:
1) |S| = Φ:
cost (2, Φ, 1) = dist(2, 1) = 10
cost (3, Φ, 1) = dist(3, 1) = 15
cost (4, Φ, 1) = dist(4, 1) = 20
cost (2, {3}, 1) = dist(2, 3) + cost (3, Φ, 1) = 35+15 = 50
cost (2, {4}, 1) = dist(2, 4) + cost (4, Φ, 1) = 25+20 = 45
cost (3, {2}, 1) = dist(3, 2) + cost (2, Φ, 1) = 35+10 = 45
cost (3, {4}, 1) = dist(3, 4) + cost (4, Φ, 1) = 30+20 = 50
cost (4, {2}, 1) = dist(4, 2) + cost (2, Φ, 1) = 25+10 = 35
cost (4, {3}, 1) = dist(4, 3) + cost (3, Φ, 1) = 30+15 = 45
cost (2, {3, 4}, 1) = min [ dist[2,3]+Cost(3,{4},1) = 35+50 = 85,
dist[2,4]+Cost(4,{3},1) = 25+45 = 70 ] = 70
cost (3, {2, 4}, 1) = min [ dist[3,2]+Cost(2,{4},1) = 35+45 = 80,
dist[3,4]+Cost(4,{2},1) = 30+35 = 65 ] = 65
cost (4, {2, 3}, 1) = min [ dist[4,2]+Cost(2,{3},1) = 25+50 = 75
dist[4,3]+Cost(3,{2},1) = 30+45 = 75 ] = 75
cost (1, {2, 3, 4}, 1) = min [ dist[1,2]+Cost(2,{3,4},1) = 10+70 = 80
dist[1,3]+Cost(3,{2,4},1) = 15+65 = 80
dist[1,4]+Cost(4,{2,3},1) = 20+75 = 95 ] = 80
So the optimal solution would be 1-2-4-3-1

Pseudo-code
Implementation in c/c++.
Here’s the implementation in C++:
Implementation in Python:
Academic solutions to tsp.
Computer scientists have spent years searching for an improved polynomial time algorithm for the Travelling Salesman Problem. Until now, the problem is still NP-hard.
Though some of the following solutions were published in recent years that have reduced the complexity to a certain degree:
- The classical symmetric TSP is solved by the Zero Suffix Method.
- The Biogeography‐based Optimization Algorithm is based on the migration strategy to solve the optimization problems that can be planned as TSP.
- Multi-Objective Evolutionary Algorithm is designed for solving multiple TSP based on NSGA-II.
- The Multi-Agent System solves the TSP of N cities with fixed resources.
Application of Traveling Salesman Problem
Travelling Salesman Problem (TSP) is applied in the real world in both its purest and modified forms. Some of those are:
- Planning, logistics, and manufacturing microchips : Chip insertion problems naturally arise in the microchip industry. Those problems can be planned as traveling salesman problems.
- DNA sequencing : Slight modification of the traveling salesman problem can be used in DNA sequencing. Here, the cities represent the DNA fragments, and the distance represents the similarity measure between two DNA fragments.
- Astronomy : The Travelling Salesman Problem is applied by astronomers to minimize the time spent observing various sources.
- Optimal control problem : Travelling Salesman Problem formulation can be applied in optimal control problems. There might be several other constraints added.
Complexity Analysis of TSP
So the total time complexity for an optimal solution would be the Number of nodes * Number of subproblems * time to solve each sub-problem. The time complexity can be defined as O(N 2 * 2^N).
- Space Complexity: The dynamic programming approach uses memory to store C(S, i), where S is a subset of the vertices set. There is a total of 2 N subsets for each node. So, the space complexity is O(2^N).
You Might Like:
- Combination Algorithm: Print all Possible Combinations of R
- Longest Common Subsequence: Python, C++ Example
- Dijsktra’s Algorithm: C++, Python Code Example
- Linear Search: Python, C++ Example
- Doubly Linked List: C++, Python Example

Travelling Salesman Problem in C and C++
Here you will learn about Travelling Salesman Problem (TSP) with example and also get a program that implements Travelling Salesman Problem in C and C++.
Travelling Salesman Problem (TSP) Using Dynamic Programming
Example problem.
Above we can see a complete directed graph and cost matrix which includes distance between each village. We can observe that cost matrix is symmetric that means distance between village 2 to 3 is same as distance between village 3 to 2.
T ( 4, {2} ) = (4,2) + T (2, {} ) 1+0 = 1
T ( 2, {3} ) = (2,3) + T (3, {} ) 2+0 = 2
Minimum distance is 7 which includes path 1->3->2->4->1.
After solving example problem we can easily write recursive equation.
Please enable JavaScript
Recursive Equation
But it is not guarantee that every vertex is connected to other vertex then we take that cost as infinity. After that we are taking minimum among all so the path which is not connected get infinity in calculation and won’t be consider.
Time Complexity
Here after reaching i th node finding remaining minimum distance to that i th node is a sub-problem.
Program for Travelling Salesman Problem in C
Enter Elements of Row: 4 3 1 5 0 The cost list is: 0 4 1 3 4 0 2 1 1 2 0 5 3 1 5 0
Program for Travelling Salesman Problem in C++
You may also like:, 48 thoughts on “travelling salesman problem in c and c++”, leave a comment cancel reply.

- Coding Problems
Travelling Salesman Problem (TSP)
Problem statement, simple approach, c++ implementation, java implementation, python implementation, travelling salesman problem using dynamic programming, c implementation of dp approach, c++ implementation of dp approach, python implementation of dp approach, java implementation of dp approach, greedy approach, c++ implementation of greedy approach, java implementation of greedy approach, python implementation of greedy approach, practice questions, frequently asked questions.
Given a set of cities and distance between every pair of cities as an adjacency matrix, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point.
Travelling Salesman Problem Example 1
Input –
Confused about your next job?
Output –
TSP Example 2 – Input –
Output – Minimum weight Hamiltonian Cycle : EACBDE= 32
- Consider city 1 as the starting and ending point. Since the route is cyclic, we can consider any point as a starting point.
- Now, we will generate all possible permutations of cities which are (n-1)!.
- Find the cost of each permutation and keep track of the minimum cost permutation.
- Return the permutation with minimum cost.
Time complexity: O(N!), Where N is the number of cities. Space complexity: O(1).
In travelling salesman problem algorithm, we take a subset N of the required cities that need to be visited, the distance among the cities dist, and starting city s as inputs. Each city is identified by a unique city id which we say like 1,2,3,4,5………n
Here we use a dynamic approach to calculate the cost function Cost(). Using recursive calls, we calculate the cost function for each subset of the original problem.
To calculate the cost(i) using Dynamic Programming , we need to have some recursive relation in terms of sub-problems.
We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset, then we calculate C(S, i) for all subsets S of size 3 and so on.
There are at most O(n2^n) subproblems, and each one takes linear time to solve. The total running time is, therefore, O(n^22^n). The time complexity is much less than O(n!) but still exponential. The space required is also exponential.
Time Complexity: O(N^2*2^N).
- First of them is a list that can hold the indices of the cities in terms of the input matrix of distances between cities
- And the Second one is the array which is our result
- Perform traversal on the given adjacency matrix tsp[][] for all the city and if the cost of reaching any city from the current city is less than the current cost the update the cost.
- Generate the minimum path cycle using the above step and return their minimum cost.
Time complexity: O(N^2*logN), Where N is the number of cities. Space complexity: O(N).
- City Tour Problem
- Shortest Common Substring
Q: Which algorithm is used for the Travelling salesman problem? A: Travelling Salesman Problem uses Dynamic programming with masking algorithm.
Q: What is the complexity of the Travelling salesman problem? A: The complexity of TSP using Greedy will be O(N^2 LogN) and using DP will be O(N^2 2^N).
Q: How is this problem modeled as a graph problem?
A: The TSP can be modeled as a graph problem by considering a complete graph G = (V, E).A tour is then a circuit in G that meets every node. In this context, tours are sometimes called Hamiltonian circuits.
Q: What is the difficulty level of the Travelling salesman problem? A: It is an NP-hard problem.
- Travelling Salesman Problem
Previous Post
Gcd of two numbers (c, python, java) with examples, difference between c and java.

- Google OR-Tools
- Bahasa Indonesia
- Español – América Latina
- Português – Brasil
- Tiếng Việt
Traveling Salesperson Problem
This section presents an example that shows how to solve the Traveling Salesperson Problem (TSP) for the locations shown on the map below.

The following sections present programs in Python, C++, Java, and C# that solve the TSP using OR-Tools
Create the data
The code below creates the data for the problem.
The distance matrix is an array whose i , j entry is the distance from location i to location j in miles, where the array indices correspond to the locations in the following order:
The data also includes:
- The number of vehicles in the problem, which is 1 because this is a TSP. (For a vehicle routing problem (VRP), the number of vehicles can be greater than 1.)
- The depot : the start and end location for the route. In this case, the depot is 0, which corresponds to New York.
Other ways to create the distance matrix
In this example, the distance matrix is explicitly defined in the program. It's also possible to use a function to calculate distances between locations: for example, the Euclidean formula for the distance between points in the plane. However, it's still more efficient to pre-compute all the distances between locations and store them in a matrix, rather than compute them at run time. See Example: drilling a circuit board for an example that creates the distance matrix this way.
Another alternative is to use the Google Maps Distance Matrix API to dynamically create a distance (or travel time) matrix for a routing problem.
Create the routing model
The following code in the main section of the programs creates the index manager ( manager ) and the routing model ( routing ). The method manager.IndexToNode converts the solver's internal indices (which you can safely ignore) to the numbers for locations. Location numbers correspond to the indices for the distance matrix.
The inputs to RoutingIndexManager are:
- The number of rows of the distance matrix, which is the number of locations (including the depot).
- The number of vehicles in the problem.
- The node corresponding to the depot.
Create the distance callback
To use the routing solver, you need to create a distance (or transit) callback : a function that takes any pair of locations and returns the distance between them. The easiest way to do this is using the distance matrix.
The following function creates the callback and registers it with the solver as transit_callback_index .
The callback accepts two indices, from_index and to_index , and returns the corresponding entry of the distance matrix.

Set the cost of travel
The arc cost evaluator tells the solver how to calculate the cost of travel between any two locations — in other words, the cost of the edge (or arc) joining them in the graph for the problem. The following code sets the arc cost evaluator.
In this example, the arc cost evaluator is the transit_callback_index , which is the solver's internal reference to the distance callback. This means that the cost of travel between any two locations is just the distance between them. However, in general the costs can involve other factors as well.
You can also define multiple arc cost evaluators that depend on which vehicle is traveling between locations, using the method routing.SetArcCostEvaluatorOfVehicle() . For example, if the vehicles have different speeds, you could define the cost of travel between locations to be the distance divided by the vehicle's speed — in other words, the travel time.
Set search parameters
The following code sets the default search parameters and a heuristic method for finding the first solution:
The code sets the first solution strategy to PATH_CHEAPEST_ARC , which creates an initial route for the solver by repeatedly adding edges with the least weight that don't lead to a previously visited node (other than the depot). For other options, see First solution strategy .
Add the solution printer
The function that displays the solution returned by the solver is shown below. The function extracts the route from the solution and prints it to the console.
The function displays the optimal route and its distance, which is given by ObjectiveValue() .
Solve and print the solution
Finally, you can call the solver and print the solution:
This returns the solution and displays the optimal route.
Run the programs
When you run the programs, they display the following output.
In this example, there's only one route because it's a TSP. But in more general vehicle routing problems, the solution contains multiple routes.
Save routes to a list or array
As an alternative to printing the solution directly, you can save the route (or routes, for a VRP) to a list or array. This has the advantage of making the routes available in case you want to do something with them later. For example, you could run the program several times with different parameters and save the routes in the returned solutions to a file for comparison.
The following functions save the routes in the solution to any VRP (possibly with multiple vehicles) as a list (Python) or an array (C++).
You can use these functions to get the routes in any of the VRP examples in the Routing section.
The following code displays the routes.
For the current example, this code returns the following route:
As an exercise, modify the code above to format the output the same way as the solution printer for the program.
Complete programs
The complete TSP programs are shown below.
Example: drilling a circuit board
The next example involves drilling holes in a circuit board with an automated drill. The problem is to find the shortest route for the drill to take on the board in order to drill all of the required holes. The example is taken from TSPLIB, a library of TSP problems.
Here's scatter chart of the locations for the holes:
The following sections present programs that find a good solution to the circuit board problem, using the solver's default search parameters. After that, we'll show how to find a better solution by changing the search strategy .
The data for the problem consist of 280 points in the plane, shown in the scatter chart above. The program creates the data in an array of ordered pairs corresponding to the points in the plane, as shown below.
Compute the distance matrix
The function below computes the Euclidean distance between any two points in the data and stores it in an array. Because the routing solver works over the integers, the function rounds the computed distances to integers. Rounding doesn't affect the solution in this example, but might in other cases. See Scaling the distance matrix for a way to avoid possible rounding issues.
Add the distance callback
The code that creates the distance callback is almost the same as in the previous example. However, in this case the program calls the function that computes the distance matrix before adding the callback.
Solution printer
The following function prints the solution to the console. To keep the output more compact, the function displays just the indices of the locations in the route.
Main function
The main function is essentially the same as the one in the previous example , but also includes a call to the function that creates the distance matrix.
Running the program
The complete programs are shown in the next section . When you run the program, it displays the following route:
Here's a graph of the corresponding route:
The OR-Tools library finds the above tour very quickly: in less than a second on a typical computer. The total length of the above tour is 2790.
Here are the complete programs for the circuit board example.
Changing the search strategy
The routing solver does not always return the optimal solution to a TSP, because routing problems are computationally intractable. For instance, the solution returned in the previous example is not the optimal route.
To find a better solution, you can use a more advanced search strategy, called guided local search , which enables the solver to escape a local minimum — a solution that is shorter than all nearby routes, but which is not the global minimum. After moving away from the local minimum, the solver continues the search.
The examples below show how to set a guided local search for the circuit board example.
For other local search strategies, see Local search options .
The examples above also enable logging for the search. While logging isn't required, it can be useful for debugging.
When you run the program after making the changes shown above, you get the following solution, which is shorter than the solution shown in the previous section .
For more search options, see Routing Options .
The best algorithms can now routinely solve TSP instances with tens of thousands of nodes. (The record at the time of writing is the pla85900 instance in TSPLIB, a VLSI application with 85,900 nodes. For certain instances with millions of nodes, solutions have been found guaranteed to be within 1% of an optimal tour.)
Scaling the distance matrix
Since the routing solver works over the integers, if your distance matrix has non-integer entries, you have to round the distances to integers. If some distances are small, rounding can affect the solution.
To avoid any issue with rounding, you can scale the distance matrix: multiply all entries of the matrix by a large number — say 100. This multiplies the length of any route by a factor of 100, but it doesn't change the solution. The advantage is that now when you round the matrix entries, the rounding amount (which is at most 0.5), is very small compared to the distances, so it won't affect the solution significantly.
If you scale the distance matrix, you also need to change the solution printer to divide the scaled route lengths by the scaling factor, so that it displays the unscaled distances of the routes.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-01-16 UTC.

Towards Data Science

Jun 14, 2020
Member-only
Notes From Industry
How to solve the traveling salesman problem — a comparative analysis, through 3 optimization methods: dynamic programming, simulated annealing, and 2-opt..
I am sure you already heard about the traveling salesman problem or TSP. There are many applications for this problem and also many solutions with different performances. Here, I want to share my recent experience to solve the traveling salesman problem, especially with the 2-opt method which is one of the easiest, yet most effective, methods to solve this problem.
If you just want to read about the 2-opt, you can jump directly to the end of this article. You can also use the Python package that I developed below to solve a TSP.
In optimization, 2-opt is a simple local search algorithm with a special swapping mechanism that suits well to solve the…
In this article, I want to share my experience in solving a TSP with 120 cities to visit. The problem had to be solved in less than 5 minutes to be used in practice. I aimed to solve this problem with the following methods:
- dynamic programming,
- simulated annealing, and
First, let me explain TSP in brief.
Artificial Intelligence: Unorthodox Lessons: How to Gain Insight and Build Innovative Solutions
Amazon.com: artificial intelligence: unorthodox lessons: how to gain insight and build innovative solutions ebook ….
www.amazon.com
Traveling Salesman Problem
The traveling salesman problem is a classic problem in combinatorial optimization. This problem is to find the shortest path that a salesman should take to traverse through a list of cities and return to the origin city. The list of cities and the distance between each pair are provided.
TSP is useful in various applications in real life such as planning or logistics. For example, a concert tour manager who wants to schedule a series of performances for the band must determine the shortest path for the tour to ensure reducing traveling costs and not make the band unnecessarily exhausted.
This is an NP-hard problem. In simple words, it means you can not guarantee to find the shortest path within a reasonable time limit. This is not unique to TSP though. In real-world optimization problems, you frequently encounter problems for which you must find sub-optimal solutions instead of optimal ones.
I. Dynamic Programming
The dynamic programming or DP method guarantees finding the best answer to TSP. However, its time complexity would exponentially increase with the number of cities. The time complexity with the DP method asymptotically equals N² × 2^N where N is the number of cities.
To give you a hint of how this time complexity increases, let me share my experiments. TSP with 10 cities can be solved by a DP method in almost 0.2 seconds using intel core i7. This number increases to almost 13 seconds (~60 times greater) with 15 cities. That is, the time complexity significantly increases even with a small increment in the number of cities.
To optimize the DP method, I could have used the memoization technique. However, the memoization technique with a large number of cities needs a 2^N × 2^N matrix that can not be easily handled in memory.
Suggestion- If you want to solve traveling salesman problem with a large number of cities the dynamic programming method is not the best choice. The DP method can guarantee the global optimum but it just needs much time and computational power that we mostly can not afford in real-world problems.
II. Simulated Annealing
Simulated Annealing or SA is a heuristic search algorithm that is inspired by the annealing mechanism in the metallurgy industry. Annealing refers to a controlled cooling mechanism that leads to the desired state of the material. But, how does this map to an optimization problem?
The lesson that optimization experts learned from the annealing mechanism is to enforce more control over the search process contrary to the gradient descent algorithm with fixed rules. The SA method has two major rules explained below.
- The moving direction must be probabilistically determined in each step with the hope of not getting trapped in a local optimum and moving toward the global optimum.
- The search step must be reduced in size while the search process is moving forward and getting close to the final result. That helps to move vigorously in early steps, and cautiously in later steps.
In the SA method, the search process must be continued until finding a good-enough solution or until reaching the stopping criteria. Plus, this method is sensitive to how its parameters including the search step and moving direction are formulated and tuned. SA method is a heuristic search algorithm and, therefore, it is sensitive to its initial point in the search space.
I implemented the SA method and tested it several times. In the end, I could not obtain a better result compared to the 2-opt method given the time constraints to execute. The 2-opt method was executed very fast.
Suggestion- The outcome of the simulated annealing method is sensitive to its parameters and its stopping criteria. A simulated annealing method is a powerful tool. But if you want to work with it, make sure you are aware of its flaws.
The 2-opt algorithm is a simple local search method with a special swapping mechanism that works as its heuristic. The main idea behind the 2-opt method is to remove path crossing in each neighborhood of cities. The 2-opt can be implemented easily and executed fast. For example, TSP with 120 cities can be solved in less than 5 seconds on the intel core i7 using this method. Here, “solved” means the algorithm converges to a good-enough solution that is a sub-optimal solution. The 2-opt method converges fast since it is deterministic in contrary to the SA method.
This method similar to other heuristic search algorithms does not guarantee to find the global optimum. The 2-opt method can be easily trapped in local optimums since it does not have a mechanism to jump out of them. Knowing all of these flaws, this method still works very well in TSP since its heuristic is very relevant, so effective, in this problem .
pdrm83/py2opt
The 2-opt method similar to other heuristic search algorithms is sensitive to its initial point in the search space. That means the final outcomes are changed by different initial points. I used a simple trick to work around this issue and to improve the results of the 2-opt method. I ran the method with different randomized initial points 10 times and selected the best result among them. By this approach, I reduced the sensitivity to the starting point to some extent.
Suggestion- The 2-opt method can be implemented easily and executed fast. Plus, it works much better than the expectation, especially when you decrease its sensitivity to the initial point in the search space. I highly suggest using this method to solve the TSP unless a good-enough result is not appropriate for you.
IV. Summary
The video below is a good summary of this article. You will enjoy watching it.
There are many methods to solve TSP. However, the above methods are the most common ones. I highly suggest the 2-opt method since it is implemented simply and executes fast. However, the simulated annealing method is very powerful if you can properly tune it and you do not have a time constraint to find the final result.
The last words- When you want to find a solution for any problem including TSP, always think about how a simple technique such as the 2-opt method can work well. Why? Because its heuristic is very well-suited to the problem.
Thanks for Reading!
If you like this post and want to support me…
- Follow me on Medium !
- Check out my books on Amazon !
- Become a member on Medium !
- Connect on Linkedin !
- Follow me on Twitter !
Join Medium with my referral link — Pedram Ataee, PhD
As a medium member, a portion of your membership fee goes to writers you read, and you get full access to every story….
pedram-ataee.medium.com
More from Towards Data Science
Your home for data science. A Medium publication sharing concepts, ideas and codes.
About Help Terms Privacy
Get the Medium app

Pedram Ataee, PhD
🤖 AI Architect 📚 Author of “Artificial Intelligence: Unorthodox Lessons” ❤️ Support my writings @ tinyurl.com/4cbeejnn
Text to speech
- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
C++ Program to Solve Travelling Salesman Problem for Unweighted Graph
Travelling Salesman Problem use to calculate the shortest route to cover all the cities and return back to the origin city. This method is use to find the shortest path to cover all the nodes of a graph.
This is the program to find shortest route of a unweighted graph.
Live Demo

0 Followers
- Related Articles
- Travelling Salesman Problem
- C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm
- C++ Program to Find Hamiltonian Cycle in an UnWeighted Graph
- C++ Program to Solve N-Queen Problem
- C++ Program to Solve a Matching Problem for a Given Specific Case
- C++ Program to Solve the Dominating Set Problem
- Write a C# program to solve FizzBuzz problem
- C++ Program to Solve the Fractional Knapsack Problem
- A Peterson Graph Problem in C Program?
- C++ Program to Solve Knapsack Problem Using Dynamic Programming
- C++ Program to Solve the 0-1 Knapsack Problem
- C++ program to Solve Tower of Hanoi Problem using Binary Value
- C Program for Activity Selection Problem
- Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm
- C Program for Number of stopping station problem


IMAGES
VIDEO
COMMENTS
The six steps of problem solving involve problem definition, problem analysis, developing possible solutions, selecting a solution, implementing the solution and evaluating the outcome. Problem solving models are used to address issues that...
When multiplying or dividing different bases with the same exponent, combine the bases, and keep the exponent the same. For example, X raised to the third power times Y raised to the third power becomes the product of X times Y raised to th...
All press is good press — until that press goes too well. Although the Netherlands’ beautiful, canal-filled city of Amsterdam garners about $91.5 billion a year through tourism, the city and its residents feel more overwhelmed than grateful...
Traveling Salesman Problem (TSP) Implementation · Consider city 1 as the starting and ending point. Since the route is cyclic, we can consider
1) Consider city 1 as the starting and ending point. · 2) Generate all (n-1)! Permutations of cities. · 3) Calculate the cost of every permutation
Algorithm for Traveling Salesman Problem · Set cost(i, , i) = 0, which means we start and end at i, and the cost is 0. · When |S| > 1, we define
Program for Travelling Salesman Problem in C ; #include<stdio.h> ; int ary[10][10],completed[10],n,cost=0; ; void takeInput(). { ; int i,j; ; printf("Enter the
Simple Approach · Consider city 1 as the starting and ending point. · Now, we will generate all possible permutations of cities which are (n-1)!.
In this video, Kodeeswaran will help you solve the Traveling Salesman Problem step by step using Dynamic Programming.
Traveling Salesperson Problem · Create the data · Create the routing model · Create the distance callback · Set the cost of travel · Set search
Travelling Salesman, by director Timothy Lanzone, is the story of four mathematicians hired by the U.S. government to solve the most elusive problem in computer
You can solve the traveling salesman problem or TSP with dynamic programming, simulated annealing, and 2-opt methods. My suggestion is the 2-opt method.
TSP is the travelling salesman problem consists of a salesperson and his travel to various cities. The salesperson must travel to each of the
Begin Define a variable vr = 4 universally. Declare an integer function TSP to implement Travelling salesman Problem. Declare a graph grph[][]