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 PickerBatting Average CalculatorRelative Standard Deviation CalculatorLine CounterFPS ConverterSort NumbersERA CalculatorMAC Address GeneratorInstagram User ID LookupRemove SpacesWord to Phone Number ConverterMAC Address LookupFeet and Inches to Cm ConverterFacebook User ID LookupRandom Truth or Dare GeneratorSum CalculatorPercent Off CalculatorBitwise CalculatorSHA256 Hash GeneratorOPS CalculatorLog Base 10 CalculatorRandom Quote GeneratorSalary Conversion CalculatorSlugging Percentage CalculatorNumber of Digits CalculatorMP3 LooperSlope and Grade CalculatorRandom IMEI GeneratorOn Base Percentage CalculatorSun, Moon & Rising Sign Calculator 🌞🌙✨Roman Numerals ConverterSquare Root (√) CalculatorVertical Jump CalculatorOctal CalculatorAudio SplitterPhone Number ExtractorCm to Feet and Inches ConverterSaturn Return CalculatorCompound Growth CalculatorMerge VideosVideo to Image ExtractorWAR CalculatorDecimal to BCD ConverterRandom Activity GeneratorCompare Two StringsBCD to Decimal ConverterFirst n Digits of PiCaffeine Overdose CalculatorRandom Poker Hand GeneratorRandom Writing Prompt GeneratorLove Compatibility CalculatorWHIP CalculatorBinary to Gray Code ConverterText FormatterCM to Inches ConverterRandom Movie PickerFile Size ConverterTime Duration CalculatorRemove AccentRandom Fake Address GeneratorQuotient and Remainder CalculatorSRT Time ShiftAI ParaphraserOutlier CalculatorRandom Superpower GeneratorImage SplitterPER CalculatorInvisible Text GeneratorRandom Number PickerVideo CropperYouTube Channel StatisticsWhat is my Lucky Number?Day of Year CalendarGray Code to Binary ConverterAI Punctuation AdderBinary to BCD ConverterIP Address to Hex ConverterNumber to Word ConverterRandom Loadout GeneratorPercent Growth Rate CalculatorConnect the Dots GeneratorRemove Leading Trailing SpacesAdd Prefix and Suffix to TextRandom Object GeneratorReverse VideoSocial Media Username CheckerWord Ladder GeneratorName Number CalculatorArc Length CalculatorVideo SplitterImage CompressorRandom Birthday GeneratorStair CalculatorMaster Number CalculatorList of Prime NumbersExponential Decay CalculatorRemove Audio from VideoSHA512 Hash GeneratorEmail ExtractorURL ExtractorDay of the Year Calculator - What Day of the Year Is It Today?Video CompressorSort Lines AlphabeticallyHex to BCD ConverterBCD to Binary ConverterLottery Number GeneratorBCD to Hex ConverterMedian CalculatorStandard Error CalculatorLeap Years ListList RandomizerBreak Line by CharactersAverage CalculatorModulo CalculatorPVIFA CalculatorHypotenuse CalculatorActual 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 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 OptimizerCTR 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 ConverterLED Resistor CalculatorVoltage Divider CalculatorParallel Resistor CalculatorCapacitor Calculator555 Timer CalculatorWire Gauge CalculatorTransformer CalculatorRC Time Constant CalculatorPower Factor CalculatorDecibel (dB) CalculatorImpedance CalculatorResonant Frequency CalculatorGrade CalculatorFinal Grade CalculatorWeighted Grade CalculatorTest Score CalculatorSignificant Figures CalculatorStudy Timer (Pomodoro)Long Division CalculatorRounding CalculatorCompleting the Square CalculatorRatio Calculatorp-Value CalculatorNormal Distribution CalculatorPercentile CalculatorFive Number Summary CalculatorCross Multiplication CalculatorLumber CalculatorRebar CalculatorPaver CalculatorInsulation CalculatorHVAC Sizing CalculatorRetaining Wall CalculatorCarpet CalculatorSquare Footage Calculator⏱️ Countdown Timer⏱️ Online Stopwatch⏱️ Hours Calculator🕐 Military Time Converter📅 Date Difference Calculator⏰ Time Card Calculator⏰ Online Alarm Clock🌐 Time Zone Converter🌬️ Wind Chill Calculator🌡️ Heat Index Calculator💧 Dew Point CalculatorFuel Cost CalculatorTire Size Calculator👙 Bra Size Calculator🌍 Carbon Footprint Calculator⬛ Aspect Ratio CalculatorOnline Notepad🖱️ Click Counter🔊 Tone Generator📊 Bar Graph Maker🥧 Pie Chart Maker📈 Line Graph Maker📷 OCR / Image to Text🔍 Plagiarism Checker🚚 Moving Cost Estimator❄️ Snow Day Calculator🎮 Game Sensitivity Converter⚔️ DPS Calculator🎰 Gacha Pity Calculator🎲 Loot Drop Probability Calculator🎮 In-Game Currency ConverterMultiplication Table GeneratorLong Multiplication CalculatorLong Addition and Subtraction CalculatorOrder of Operations Calculator (PEMDAS)Place Value Chart GeneratorNumber Pattern FinderEven or Odd Number CheckerAbsolute Value CalculatorCeiling and Floor Function CalculatorUnit Rate CalculatorSkip Counting GeneratorNumber to Fraction ConverterEstimation CalculatorCubic Equation SolverQuartic Equation SolverLogarithmic Equation SolverExponential Equation SolverTrigonometric Equation SolverLiteral Equation SolverRational Equation SolverSystem of Nonlinear Equations SolverPoint-Slope Form CalculatorStandard Form to Slope-Intercept ConverterEquation of a Line CalculatorParallel and Perpendicular Line CalculatorDescartes' Rule of Signs CalculatorRational Root Theorem CalculatorSigma Notation Calculator (Summation)Product Notation Calculator (Pi Notation)Pascal's Triangle GeneratorBinomial Theorem Expansion CalculatorParabola CalculatorHyperbola CalculatorConic Section IdentifierRegular Polygon CalculatorIrregular 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 Checker