Skip to content

πŸš€βœ¨ TSP Solver β€” Exact & heuristic algorithms πŸ§©πŸ“Š to tackle Traveling Salesman Problem πŸš—πŸ’¨! Includes DP, Backtracking, Branch & Bound, Christofides, Simulated Annealing πŸ”₯πŸŽ―πŸ“ˆ!

License

Notifications You must be signed in to change notification settings

muhammadIdhamMaarif/Traveling-Salesman-Problem-CPP

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Traveling Salesman Problem (TSP) Solver

License: MIT


TL;DR

  1. Copy all text in pnr.cpp
  2. Open Programiz C++ Compiler
  3. Paste the code
  4. Run

Overview

This repository provides a comprehensive C++ implementation of multiple algorithms to solve the Traveling Salesman Problem (TSP) β€” a classic NP-hard combinatorial optimization problem.

The repository is designed as a single C++ class TSP that encapsulates various algorithms, including:

  • Backtracking (with and without fixed start city)
  • Backtracking with mirror elimination (reduces symmetric duplicates)
  • Dynamic Programming (Held-Karp algorithm)
  • Branch and Bound
  • Nearest Neighbor heuristic
  • Greedy Edge Selection heuristic
  • Christofides Algorithm (approximation algorithm with 3/2 approximation guarantee)
  • Simulated Annealing (metaheuristic)

Each algorithm has different time and space complexity characteristics, providing a trade-off between accuracy and performance.


Repository Contents

  • tsp.hpp β€” Header-only class file with all TSP algorithms implemented in a class
  • main.cpp β€” Sample usage demonstrating each algorithm
  • pnr.cpp β€” Paste and run code to test directly in compiler
  • LICENSE β€” MIT License file
  • README.md β€” This file

Kompleksitas Algoritma

Berikut adalah analisis singkat kompleksitas waktu dan ruang untuk berbagai metode penyelesaian TSP yang ada di kelas ini:

Algoritma Time Complexity Space Complexity Deskripsi Singkat
SolveWithNonFixedFirstCity() O(n!) O(n) Mengeksplorasi semua permutasi rute, sangat mahal untuk n besar.
SolveWithFixedFirstCity() O((n-1)!) O(n) Mengurangi permutasi dengan mengunci kota awal, mempercepat sekitar faktor n.
SolveWithEliminatingMirror() O((n-1)! / 2) O(n) Menghilangkan rute yang simetris terbalik, mengurangi permutasi sekitar setengahnya.
SolveWithDynamicProgramming() O(nΒ² * 2^n) O(n * 2^n) Algoritma DP bitmask efisien, cocok untuk n sampai sekitar 20.
SolveWithBranchAndBound() Worst: O(n!), Avg: ? O(n) Pruning mengurangi cabang pencarian, sangat tergantung pada input dan bound.
SolveWithNearestNeighbor() O(nΒ²) O(n) Heuristik cepat, hasil tidak selalu optimal.
SolveWithGreedyEdgeSelection() O(nΒ² log n) O(nΒ²) Membangun siklus Hamiltonian dari edge murah, menggunakan sorting dan Union-Find.
SolveWithChristofidesAlgorithm() O(nΒ³) O(nΒ²) Aproksimasi dengan jaminan 1.5x solusi optimal, memakai MST dan matching.
SolveWithSimulatedAnnealingAlgorithm() O(iterations * n) O(n) Heuristik probabilistik, iterasi tergantung parameter, cocok untuk n besar.

Keterangan:

  • n = jumlah kota (numCities)
  • iterations = parameter jumlah iterasi pada algoritma Simulated Annealing
  • Pruning di Branch and Bound membuat waktu rata-rata sulit diprediksi secara pasti

Algorithms Explained

1. Backtracking (Permutation Enumeration)

  • Methods: SolveWithNonFixedFirstCity(), SolveWithFixedFirstCity()
  • Idea: Generates all permutations of city orders, computes total distance, and tracks the shortest.
  • Complexity:
    • Non-fixed start: ( O(n!) )
    • Fixed first city: ( O((n-1)!) ) (reduces duplicates by fixing start)
  • Reference:

2. Mirror Elimination

  • Method: SolveWithEliminatingMirror()
  • Idea: Avoids counting routes that are reversals of each other (which have same cost in symmetric TSP), further cutting search space roughly in half.
  • Effect: Reduces permutations from ( (n-1)! ) to approximately ( \frac{(n-1)!}{2} ).
  • Reference:
    • Papadimitriou and Steiglitz, Combinatorial Optimization: Algorithms and Complexity

3. Dynamic Programming (Held-Karp)

  • Method: SolveWithDynamicProgramming()
  • Idea: Uses bitmask DP to remember the shortest path to reach a set of visited cities ending at a particular city.
  • Complexity: ( O(n^2 2^n) ) time and space β€” still exponential but much better than brute force.
  • Reference:
    • Held and Karp, "A Dynamic Programming Approach to Sequencing Problems", J. SIAM, 1962
    • Held-Karp Wikipedia

4. Branch and Bound

  • Method: SolveWithBranchAndBound()
  • Idea: Uses bounding techniques to prune large parts of the search space by estimating lower bounds on route cost.
  • Complexity: Varies β€” faster than brute force in practice but worst case still factorial.
  • Reference:

5. Nearest Neighbor Heuristic

  • Method: SolveWithNearestNeighbor()
  • Idea: Start at a city and repeatedly visit the nearest unvisited city until all visited.
  • Complexity: ( O(n^2) )
  • Approximation: Can be arbitrarily bad in worst cases but very fast.
  • Reference:

6. Greedy Edge Selection Heuristic

  • Method: SolveWithGreedyEdgeSelection()
  • Idea: Selects edges in order of increasing length, adding them if they don't form a cycle or cause degree > 2 until a Hamiltonian cycle forms.
  • Complexity: ( O(n^2 \log n) )
  • Reference:

7. Christofides Algorithm

  • Method: SolveWithChristofidesAlgorithm()
  • Idea:
    • Construct minimum spanning tree (MST)
    • Find minimum-weight perfect matching on odd degree vertices
    • Combine MST and matching to form Eulerian multigraph
    • Shortcut Eulerian tour to Hamiltonian cycle
  • Guarantee: 3/2 approximation factor for metric TSP
  • Complexity: Polynomial
  • Reference:

8. Simulated Annealing (Metaheuristic)

  • Method: SolveWithSimulatedAnnealingAlgorithm()
  • Idea: Probabilistically explores the solution space, occasionally accepting worse solutions to escape local minima, gradually reducing "temperature" to converge.
  • Complexity: Depends on parameters, typically much faster than exact methods for large ( n ).
  • Reference:

How to Use (Local)

  1. Clone the repo:
git clone https://github.com/muhammadIdhamMaarif/Traveling-Salesman-Problem-CPP.git
cd Traveling-Salesman-Problem-CPP
  1. Compile (requires C++11 or later):
g++ -std=c++17 pnr.cpp -o pnr
  1. Run:
./pnr

You will see outputs of all algorithms running on the sample distance matrix.

How to Use (Paste and Run)

  1. Open pnr.cpp
  2. Copy all the contents inside
  3. Paste in your code editor or online compiler (Example Programiz)

How to Use (Header)

  1. Copy all the contents inside tsp.hpp
  2. Paste into your workspace
  3. Use by using
  #include "tsp.hpp"
  // your code

Theoretical Notes and Proof Sketches

  • Brute force correctness: Enumerates all permutations, so guaranteed to find optimal.
  • Held-Karp correctness: Uses optimal substructure and overlapping subproblems, proven via DP theory.
  • Branch and Bound correctness: Prunes safely by bounding costs, maintains optimality.
  • Christofides approximation: Guaranteed ≀ 1.5 Γ— OPT on metric TSP by MST and matching proofs.
  • Simulated Annealing convergence: Probabilistically guaranteed to converge to global optimum as temperature β†’ 0 and infinite iterations, practically a heuristic.

License

This project is licensed under the MIT License β€” see LICENSE file for details.

Contributions

Contributions and improvements are welcome! Feel free to open issues or submit pull requests.

References

Core Algorithm References

Backtracking and Dynamic Programming

Nearest Neighbor and Heuristics

Christofides Algorithm

Simulated Annealing

Ant Colony Optimization

Genetic Algorithms

Comprehensive Collections

Educational Programming Resources

GeeksforGeeks

W3Schools and TutorialsPoint

Academic and Technical Platforms

Python, NetworkX, and Related Tools

MATLAB & MathWorks

R & CRAN

Programming Blogs and Tutorials

Competitive Programming Platforms

Others

  • Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2009). Introduction to algorithms (3rd ed.). MIT Press.
  • Papadimitriou, C. H., & Steiglitz, K. (1998). Combinatorial optimization: Algorithms and complexity. Dover Publications.
  • Saller, S., Hougardy, S., & Vygen, J. (2024). Approximation algorithms for traveling salesman problems: A systematic review. Mathematical Programming, 204(1), 1–89.

About

πŸš€βœ¨ TSP Solver β€” Exact & heuristic algorithms πŸ§©πŸ“Š to tackle Traveling Salesman Problem πŸš—πŸ’¨! Includes DP, Backtracking, Branch & Bound, Christofides, Simulated Annealing πŸ”₯πŸŽ―πŸ“ˆ!

Topics

Resources

License

Stars

Watchers

Forks

Languages