Simplify Your Workflow: Search MiniWebtool.
Add Extension
Home Page > Math > Advanced Math Operations > Traveling Salesman Solver (TSP)

Traveling Salesman Solver (TSP)

Find the shortest tour that visits every city exactly once and returns to the start. Exact dynamic programming (Held-Karp) for small instances and nearest-neighbor + 2-opt heuristics for larger ones. Accepts coordinates or a distance matrix and renders an animated SVG tour.

Traveling Salesman Solver (TSP)
Coordinate lines: A, 10, 20 or 10 20. Matrix rows: 0 10 15 20 — one row per line, square, non-negative. Max 40 cities.
Comma- or space-separated labels, one per matrix row. Defaults to A, B, C… if omitted.

Embed Traveling Salesman Solver (TSP) Widget

About Traveling Salesman Solver (TSP)

The Traveling Salesman Solver is a practical, educational calculator for the classic Traveling Salesman Problem (TSP): given a set of cities and pairwise distances, find the shortest possible tour that visits every city exactly once and returns to the start. This solver accepts either planar coordinates or a custom distance matrix, selects the best algorithm automatically based on problem size, and renders the resulting tour as an animated SVG map.

What Is the Traveling Salesman Problem?

Formally, given a complete weighted graph G = (V, E) with vertex set V = {1, 2, ..., n} and edge weights d(i, j), TSP seeks a permutation π of the vertices that minimizes:

minimize Σi=1n-1 d(π(i), π(i+1)) + d(π(n), π(1))

The final term closes the loop. TSP is one of the oldest and most studied problems in combinatorial optimization — it is NP-hard in the general case, meaning no known algorithm solves every instance in polynomial time. Despite that, it appears in countless real-world applications: vehicle routing, PCB drilling, DNA sequencing, warehouse picking routes, astronomical observation schedules, and even rural postal delivery.

How This Solver Works

Held–Karp Dynamic Programming (Exact)

For small instances (up to 12 cities) the solver computes the provably optimal tour using the Held–Karp algorithm, published independently by Richard Bellman and Michael Held & Richard Karp in 1962. The key recurrence, where C(S, j) is the shortest path from vertex 1 to vertex j visiting exactly the subset S:

C(S, j) = mink ∈ S \ {j} [ C(S \ {j}, k) + d(k, j) ]

The optimal tour cost is then minj [C({1,...,n}, j) + d(j, 1)]. Held–Karp runs in O(2n · n²) time and O(2n · n) memory — a huge improvement over brute force n!, but still exponential. Past roughly 20 cities the memory footprint becomes impractical.

Nearest-Neighbor + 2-opt (Heuristic)

For larger instances the solver uses a two-stage heuristic. First, Nearest-Neighbor constructs a quick tour by greedily walking to the closest unvisited city from each starting vertex. The solver tries many starting vertices and keeps the best tour. Then 2-opt local search improves the tour by iteratively removing two edges and reconnecting the two resulting paths in the only other possible way:

Before: ... a — b ... c — d ... After 2-opt swap: ... a — c ... b — d ... If d(a,c) + d(b,d) < d(a,b) + d(c,d) → accept swap, reverse the subtour b..c

Geometrically, 2-opt removes every "crossing" in the tour: any two crossing segments can always be uncrossed for a shorter total length. The algorithm stops at a local optimum where no single swap helps, called a 2-optimal tour. On realistic Euclidean instances 2-opt typically finds tours within 2–5% of the true optimum in milliseconds.

Input Formats

Coordinate mode (x, y)

One city per line. Each line is label, x, y — label is optional. The solver computes Euclidean distances automatically and visualizes cities at their true positions.

A, 10, 20 B, 40, 70 C, 75, 30 Paris: 2.35, 48.86 10 20 ← auto-labeled C1

Distance matrix mode

An n × n square matrix of non-negative distances, one row per line, values separated by spaces or commas. Matrices may be symmetric or asymmetric — asymmetric matrices model one-way streets, flight prices with varying availability, and wind-dependent travel. Optionally provide labels in the Matrix labels field.

0 10 15 20 10 0 35 25 15 35 0 30 20 25 30 0

Algorithm Comparison

Algorithm Time complexity Memory Result quality Practical size
Brute force O(n!) O(n) Optimal n ≤ 10
Held–Karp DP O(2n · n²) O(2n · n) Optimal n ≤ 20
Nearest-Neighbor O(n²) O(n) ~25% worse than optimal n ≤ thousands
NN + 2-opt O(n² · passes) O(n) ~2–5% worse than optimal n ≤ hundreds

How to Use This Solver

  1. Pick an input mode. Coordinates if your cities have meaningful (x, y) positions; Distance matrix if your costs are non-Euclidean or asymmetric.
  2. Paste or type your data. One city or row per line. Click a quick-example button above the form to prefill a valid example.
  3. Choose the algorithm. Leave on Auto for the right default: Held–Karp when the instance is small enough for provable optimality, NN + 2-opt otherwise. Force a specific algorithm if you want to compare.
  4. Choose closed or open. A closed tour returns to the start — the traditional TSP. Open path mode solves the related Hamiltonian Path problem where the salesperson ends at a different city.
  5. Click Solve. The result page shows the total tour length, an animated SVG of the route (click "Replay animation" to replay it), the full city sequence, a per-edge breakdown, and the distance matrix with tour edges highlighted.

Worked Example

Consider five cities — a rectangle plus a peak: A (0, 0), B (4, 0), C (4, 3), D (0, 3), E (2, 5). The solver returns:

Real-World Applications

Frequently Asked Questions

What is the Traveling Salesman Problem?

The Traveling Salesman Problem (TSP) asks for the shortest possible tour that visits every city exactly once and returns to the starting city. It is one of the most famous problems in combinatorial optimization and is NP-hard in the general case, meaning no known algorithm solves every instance in polynomial time.

What is the Held–Karp algorithm?

Held–Karp is a dynamic-programming algorithm that solves TSP exactly in O(2n · n²) time and O(2n · n) memory. It is dramatically faster than brute force (n factorial) but still exponential, so in practice it is only used for instances up to around 20 cities. This solver uses Held–Karp when there are 12 or fewer cities.

What is 2-opt and why is it used?

2-opt is a local-search heuristic that repeatedly removes two edges from the current tour and reconnects the two resulting paths in the other possible way. When the new tour is shorter, the swap is kept. 2-opt runs in polynomial time per iteration and consistently finds tours within a few percent of the optimal, which is why it is the classic go-to heuristic for larger TSP instances.

When should I use coordinates versus a distance matrix?

Use coordinates when your cities live in a plane with straight-line distances — for example points on a map, warehouse locations, or drill holes on a circuit board. Use a distance matrix when the pairwise cost is not Euclidean — for example flight prices, travel times with traffic, one-way road distances, or asymmetric costs. The matrix mode accepts any non-negative distances, even asymmetric ones.

Is the 2-opt solution optimal?

No, 2-opt returns a 2-optimal tour, meaning no single pair of edges can be swapped to produce a shorter route. This is a local optimum and usually within a few percent of the global optimum on well-behaved instances, but it is not guaranteed to be the global best. For a provably optimal tour on small instances, choose Held–Karp.

Does this tool support asymmetric distance matrices?

Yes. In Distance matrix mode you can enter any non-negative square matrix, including asymmetric ones where D[i][j] differs from D[j][i]. Held–Karp and 2-opt both handle asymmetric matrices correctly. This is useful for real-world routing problems with one-way streets, traffic, or wind-dependent flight costs.

Further Reading

Reference this content, page, or tool as:

"Traveling Salesman Solver (TSP)" at https://MiniWebtool.com/traveling-salesman-solver-tsp/ from MiniWebtool, https://MiniWebtool.com/

by miniwebtool team. Updated: Apr 21, 2026

You can also try our AI Math Solver GPT to solve your math problems through natural language question and answer.

Related MiniWebtools:

Advanced Math Operations:

Top & Updated:

Random PickerRandom Name PickerLine CounterBatting Average CalculatorRelative Standard Deviation CalculatorFPS ConverterSort NumbersERA CalculatorMAC Address GeneratorRemove SpacesInstagram User ID LookupWord to Phone Number ConverterFacebook User ID LookupMAC Address LookupSum CalculatorFeet and Inches to Cm ConverterOPS CalculatorJob FinderRandom Truth or Dare GeneratorRandom Quote GeneratorPercent Off CalculatorSHA256 Hash GeneratorBitwise CalculatorSquare Root (√) CalculatorDoubling Time CalculatorLog Base 10 CalculatorVertical Jump CalculatorNumber of Digits CalculatorRoman Numerals ConverterMP3 LooperAudio SplitterSalary Conversion CalculatorSlope and Grade CalculatorSlugging Percentage CalculatorSaturn Return CalculatorOn Base Percentage CalculatorPhone Number ExtractorRandom IMEI GeneratorRandom Poker Hand GeneratorNumber to Word ConverterMerge VideosAI Text HumanizerCompare Two StringsCaffeine Overdose CalculatorSun, Moon & Rising Sign Calculator 🌞🌙✨Compound Growth CalculatorDecimal to BCD ConverterFirst n Digits of PiImage ResizerRandom Birthday GeneratorBinary to Gray Code ConverterCm to Feet and Inches ConverterClothing Size ConverterWHIP CalculatorGrade CalculatorBCD to Decimal ConverterAdd Prefix and Suffix to TextRandom Fake Address GeneratorRandom Activity GeneratorOctal CalculatorOne Rep Max (1RM) CalculatorVideo to Image ExtractorWAR CalculatorRandom Movie PickerFile Size ConverterRandom Superpower GeneratorText FormatterYouTube Channel StatisticsInvisible Text GeneratorTime Duration CalculatorRemove AccentOutlier CalculatorRandom Writing Prompt GeneratorPercent Growth Rate CalculatorQuotient and Remainder CalculatorLove Compatibility CalculatorStair CalculatorCM to Inches ConverterRandom Object GeneratorRandom Integer GeneratorDay of Year CalendarList of Prime NumbersCryptogram GeneratorWord Ladder GeneratorImage SplitterRemove Leading Trailing SpacesAdd Text to ImageArc Length CalculatorGray Code to Binary ConverterAI Punctuation AdderConnect the Dots GeneratorRandom Loadout GeneratorBingo Card GeneratorExponential Decay CalculatorModulo CalculatorSHA512 Hash GeneratorImage CompressorMaster Number CalculatorVideo CropperEmail ExtractorURL ExtractorAI ParaphraserDay of the Year Calculator - What Day of the Year Is It Today?Video CompressorBinary to BCD ConverterIP Address to Hex ConverterSort Lines AlphabeticallyHex to BCD ConverterBCD to Binary ConverterLottery Number GeneratorBCD to Hex ConverterMedian CalculatorStandard Error CalculatorLeap Years ListList RandomizerBreak Line by CharactersAverage CalculatorPVIFA CalculatorReverse VideoHypotenuse CalculatorRemove Audio from VideoActual Cash Value CalculatorScientific Notation to Decimal ConverterNumber ExtractorAngel Number CalculatorLog Base 2 CalculatorRoot Mean Square CalculatorSum of Positive Integers CalculatorSHA3-256 Hash GeneratorAI Sentence Expander📅 Date CalculatorLbs to Kg ConverterHex to Decimal ConverterRandom Group GeneratorConvolution CalculatorMAC Address AnalyzerRandom String GeneratorAmortization CalculatorMarkup CalculatorPVIF CalculatorName Number CalculatorDecimal to Hex ConverterInstagram Font GeneratorSocial Media Image Size GuideTikTok Money CalculatorTwitter/X Character CounterTwitter/X Timestamp ConverterYouTube Watch Time CalculatorTwitch Earnings CalculatorYouTube Shorts Monetization CalculatorFacebook Ad Cost CalculatorSocial Media ROI CalculatorSocial Media Post Time OptimizerSocial Media Username CheckerCTR CalculatorROAS CalculatorInfluencer ROI CalculatorForce CalculatorAcceleration CalculatorVelocity CalculatorMomentum CalculatorProjectile Motion CalculatorKinetic Energy CalculatorPotential Energy CalculatorWork and Power CalculatorDensity CalculatorPressure CalculatorIdeal Gas Law CalculatorFree Fall CalculatorTorque CalculatorHorsepower CalculatorDilution CalculatorChemical Equation BalancerStoichiometry CalculatorPercent Yield CalculatorEmpirical Formula CalculatorBoiling Point CalculatorTitration CalculatorMole/Gram/Particle ConverterIrregular Polygon Area CalculatorFrustum CalculatorTorus Calculator3D Distance CalculatorGreat Circle Distance CalculatorCircumscribed Circle (Circumcircle) CalculatorInscribed Circle (Incircle) CalculatorAngle Bisector CalculatorTangent Line to Circle CalculatorHeron's Formula CalculatorCoordinate Geometry Distance CalculatorVolume of Revolution CalculatorSurface of Revolution CalculatorParametric Curve GrapherRiemann Sum CalculatorTrapezoidal Rule CalculatorSimpson's Rule CalculatorImproper Integral CalculatorL'Hôpital's Rule CalculatorMaclaurin Series CalculatorPower Series CalculatorSeries Convergence Test CalculatorInfinite Series Sum CalculatorAverage Rate of Change CalculatorInstantaneous Rate of Change CalculatorRelated Rates SolverOptimization Calculator (Calculus)Gradient Calculator (Multivariable)Divergence CalculatorCurl CalculatorLine Integral CalculatorSurface Integral CalculatorJacobian Matrix CalculatorNewton's Method CalculatorRREF Calculator (Row Echelon Form)Matrix Inverse CalculatorMatrix Multiplication CalculatorDot Product CalculatorCross Product CalculatorVector Magnitude CalculatorUnit Vector CalculatorAngle Between Vectors CalculatorNull Space CalculatorColumn Space CalculatorCramer's Rule CalculatorMatrix Diagonalization CalculatorQR Decomposition CalculatorCholesky Decomposition CalculatorMatrix Power CalculatorCharacteristic Polynomial CalculatorBayes' Theorem CalculatorF-Test / F-Distribution CalculatorHypergeometric Distribution CalculatorNegative Binomial Distribution CalculatorGeometric Distribution CalculatorExponential Distribution CalculatorWeibull Distribution CalculatorBeta Distribution CalculatorSpearman Rank Correlation CalculatorFisher's Exact Test CalculatorContingency Table CalculatorOdds Ratio CalculatorRelative Risk CalculatorEffect Size CalculatorPermutations with Repetition CalculatorModular Exponentiation CalculatorPrimitive Root CalculatorPerfect Number CheckerAmicable Number CheckerTwin Prime FinderMersenne Prime CheckerGoldbach Conjecture VerifierMöbius Function CalculatorEgyptian Fraction CalculatorFibonacci Number CheckerDigital Root CalculatorPartition Function CalculatorBoolean Algebra SimplifierKarnaugh Map (K-Map) SolverLogic Gate SimulatorGraph Coloring CalculatorTopological Sort CalculatorAdjacency Matrix CalculatorRecurrence Relation SolverInclusion-Exclusion CalculatorLinear Programming SolverTraveling Salesman Solver (TSP)Hamiltonian Path CheckerPlanar Graph CheckerNetwork Flow Calculator (Max Flow)Stable Marriage Problem SolverFirst-Order ODE SolverSecond-Order ODE SolverDirection Field / Slope Field PlotterEuler's Method CalculatorBernoulli ODE SolverSystem of ODEs SolverGroup Theory Order CalculatorRing and Field CalculatorJordan Normal Form CalculatorMatrix Exponential CalculatorTensor Product CalculatorFast Fourier Transform (FFT) CalculatorZ-Transform CalculatorNumerical Integration CalculatorTOML to JSON ConverterJSON to CSV ConverterXML to JSON ConverterSQL to MongoDB Query ConverterCSS Flexbox PlaygroundCSS Grid GeneratorJWT GeneratorBcrypt Hash Generator / CheckerColor Code Converter (All Formats)Git Command Generator.env File GeneratorLorem Picsum / Placeholder Image GeneratorText to Binary/Hex/ASCII ConverterSyllable CounterSentence CounterParagraph CounterSpeaking Time CalculatorReading Time CalculatorWhitespace VisualizerStrikethrough Text GeneratorTorque Converter (Nm, ft-lb, kgf-cm)Data Transfer Rate ConverterFuel Efficiency ConverterAstronomical Unit ConverterRing Size ConverterPaper Size ReferenceGas Mileage CalculatorEV Range CalculatorEV Charging Time Calculator0–60 / Quarter Mile CalculatorCar Lease CalculatorVehicle Towing Capacity CalculatorExposure Triangle CalculatorCrop Factor CalculatorMegapixel to Print Size CalculatorPhoto File Size EstimatorMusic BPM TapperMusic Key TransposerVideo Bitrate CalculatorSeed Germination Rate CalculatorFertilizer Calculator (NPK)Raised Bed Soil CalculatorFrost Date CalculatorLawn Fertilizer CalculatorCompost Calculator (C:N Ratio)Solar Panel CalculatorSolar ROI CalculatorHome Energy Audit CalculatorAppliance Energy Cost CalculatorWater Usage CalculatorElectricity Generation Cost CalculatorHeat Loss CalculatorFlight Distance CalculatorTravel Budget CalculatorJet Lag CalculatorPacking List GeneratorTip Splitter (Advanced)Lease vs Buy CalculatorHourly Rate Calculator (Freelancer)Invoice Late Fee CalculatorESPP CalculatorStock Split CalculatorOptions Probability CalculatorDollar to Gold ConverterBeam Load CalculatorPipe Flow CalculatorBolt Torque CalculatorSteel Weight CalculatorGravel, Sand & Topsoil CalculatorRandom Sentence GeneratorRandom Paragraph GeneratorRandom Math Problem GeneratorRandom Bible Verse GeneratorRandom Cat/Dog Name GeneratorRandom Debate Topic GeneratorBody Recomposition CalculatorAlcohol Calorie CalculatorMedication Dosage CalculatorPace to Calories CalculatorHydration CalculatorTrain Meeting Problem SolverAge Word Problem SolverMixture Problem SolverWork Rate Problem SolverDistance-Speed-Time Triangle Calculator