← Back to BHK docs

teeline · algorithms/bhk

Bellman-Held-Karp — exact dynamic programming

BHK fills a table of subset costs: dp[mask][i] is the cheapest path from city 0 that visits exactly the cities in mask and ends at city i. Every cell is built from one smaller subset plus one edge — then the optimal route is read back through the recorded predecessors.

end \ subset00001000100001100100001010011000111010000100101010010110110001101011100111110000100011001010011101001010110110101111100011001110101101111100111011111011111
1180······························
2·255·····························
3···180···························
4·······90·······················
5···············201···············
012345
click a cell to see how its value was computed
— (after the table fills)
subset size
2
bits set
00011
phase
forward
step
0
base cell filled next cell optimal route
Bellman-Held-Karp — the DP table fills subset by subset
Speed
cities: 6dp[mask][i] = min_j dp[mask∖{i}][j] + d(j, i)