The tour that grows too quickly.
Solve a tiny instance exactly and understand why a brute-force plan does not scale.
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 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.
FIX the starting vertex
ENUMERATE every ordering of the others
ADD the return edge
KEEP the cheapest complete tour03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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])80
- 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
The contract assumes a complete cost matrix with meaningful finite costs. Missing edges require an explicit impossibility representation and no-route handling.
- 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
O(n·(n−1)!) for this enumeration
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
Calculate the cost of the candidate tour 0→1→3→2→0 for the example matrix.
Reveal one possible solution +
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
Does a quick nearest-neighbour tour always solve TSP optimally?
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.