Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Algorithm design patterns
EXPERIMENT 55 / 66

The tour that grows too quickly.

Solve a tiny instance exactly and understand why a brute-force plan does not scale.

BY NAVAN SAMI◷ 9 MIN READSTRETCHALGORITHM

01 Model the idea

The traveling salesperson problem asks for a minimum-cost tour that visits every vertex once and returns to the start. Fixing a start removes equivalent rotations, but enumerating the remaining permutations still grows factorially. A tiny exact solver is useful as a test oracle for heuristics on small instances. It is not a practical large-route planning engine.

THE THING THAT MUST STAY TRUE

The saved best is the cheapest complete candidate examined so far.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
FIX the starting vertex
ENUMERATE every ordering of the others
ADD the return edge
KEEP the cheapest complete tour

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

traveling_salesman.py
from itertools import permutations
def best_tour(cost):
    n = len(cost)
    if n == 0: return 0, []
    best, route = float("inf"), None
    for middle in permutations(range(1, n)):
        candidate = (0,) + middle + (0,)
        total = sum(cost[a][b] for a, b in zip(candidate, candidate[1:]))
        if total < best: best, route = total, candidate
    return best, route
cost = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]
print(best_tour(cost)[0])
↳ EXPECTED OUTPUT
80
  1. 1

    Each permutation proposes a complete visit order. The return edge is included explicitly, so the result is a tour rather than an open path.

  2. 2

    The contract assumes a complete cost matrix with meaningful finite costs. Missing edges require an explicit impossibility representation and no-route handling.

  3. 3

    General exact TSP optimisation is NP-hard. Dynamic programming can reduce the factorial search to an exponential subset-state algorithm, but that still limits instance size.

04 Count the cost

TIME

O(n·(n−1)!) for this enumeration

SPACE

O(n) working candidate state, excluding the input matrix

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Calculate the cost of the candidate tour 0→1→3→2→0 for the example matrix.

Reveal one possible solution +
one_possible_solution.py
cost = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]
route = [0, 1, 3, 2, 0]
print(sum(cost[a][b] for a, b in zip(route, route[1:])))

06 Check your reasoning

QUICK SIGNAL CHECK

Does a quick nearest-neighbour tour always solve TSP optimally?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.