|
| 1 | +/* |
| 2 | +Held-karp algorithm (https://en.wikipedia.org/wiki/Held-Karp_algorithm) |
| 3 | +
|
| 4 | +- Held-karp algorithm solves the TSP problem using a dynamic programming paradigm. |
| 5 | +- It computes the minimum cost to visit each city exactly once & return to the start point, |
| 6 | + considering all subsets of cities & using memoization. |
| 7 | +- Comparing it with the Hamiltonian algorithm vs Held-karp algorithm ( n! vs ~2^n), this is more efficient. |
| 8 | +*/ |
| 9 | + |
| 10 | +function heldKarp(dist) { |
| 11 | + const n = dist.length |
| 12 | + const memo = Array.from({ length: n }, () => Array(1 << n).fill(null)) |
| 13 | + |
| 14 | + // Base case: distance from the starting point to itself is 0 |
| 15 | + for (let i = 0; i < n; i++) { |
| 16 | + memo[i][1 << i] = dist[i][0] |
| 17 | + } |
| 18 | + |
| 19 | + // Iterate through all subsets of vertices |
| 20 | + for (let mask = 0; mask < (1 << n); mask++) { |
| 21 | + for (let u = 0; u < n; u++) { |
| 22 | + if (!(mask & (1 << u))) continue // u must be in the subset |
| 23 | + // Iterate through all vertices to find the minimum cost |
| 24 | + for (let v = 0; v < n; v++) { |
| 25 | + if (mask & (1 << v) || u === v) continue; // v must not be in the subset |
| 26 | + const newMask = mask | (1 << v) |
| 27 | + const newCost = memo[u][mask] + dist[u][v] |
| 28 | + |
| 29 | + if (memo[v][newMask] === null || newCost < memo[v][newMask]) { |
| 30 | + memo[v][newMask] = newCost |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + let minCost = Infinity |
| 37 | + for (let u = 1; u < n; u++) { |
| 38 | + const cost = memo[u][(1 << n) - 1] + dist[u][0] |
| 39 | + minCost = Math.min(minCost, cost) |
| 40 | + } |
| 41 | + |
| 42 | + return minCost |
| 43 | +} |
| 44 | + |
| 45 | +export { heldKarp } |
0 commit comments