Skip to content

Commit a842ee9

Browse files
authored
Add files via upload
1 parent 55ff0ad commit a842ee9

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Backtracking/held_karp.js

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

0 commit comments

Comments
 (0)