Overview
Naive TSP checks all permutations of paths, taking `O(N!)`. This becomes impossible around N=12. DP with Bitmasking allows us to solve up to N=20.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the shortest possible route that visits every node exactly once and returns to the origin node. We use Bitmask DP to reduce O(N!) time to O(N² * 2^N).
Naive TSP checks all permutations of paths, taking `O(N!)`. This becomes impossible around N=12. DP with Bitmasking allows us to solve up to N=20.
The state needs two things: `u` (Where are we currently?) and `mask` (Which nodes have we already visited?).
From node `u`, try visiting every unvisited node `v`. The cost is `dist[u][v] + tsp(v, mask | (1 << v))`.
When `mask == (1 << N) - 1`, all bits are 1, meaning all nodes are visited. The only thing left is to return to the start node (usually Node 0), so return `dist[u][0]`.