Search code examples
javascriptalgorithmbit-manipulationgraph-algorithmbit-shift

Iterate through all potential starting positions in Held-karp algorithm utilizing a bit-mask


I am interested in implementing the held-karp algorithm based on a C implementation found here: https://www.math.uwaterloo.ca/~bico/papers/comp_chapterDP.pdf in javascript. However, this implementation uses only a single starting position. I have tried numerous methods for moving through all starting positions (all nodes in the graph), however, because the implementation uses a bitmask as the set of visited nodes, starting positions 1 and 0 will not change through each call of the function solve because 0 & anynumber will always be 0.

function tsp_hk(dist){
    let n = dist.length;
    let opt = []; //array [endPoint][set] representing the optimum paths
    //Initialize array values
    for(let i = 0; i < n; i++){
        opt[i] = [];
        opt[i][1 << (i)] = dist[i][n-1];
    }

    function solve(set, end){
        if(opt[end][set] === undefined){
            let R = set & ~(1 << end);
            let minv = 99999;
            for (let i = 0; i < n; i++){
                if(!(R & (1 << i))) continue;
                let s = solve(R, i);
                let v = s + dist[i][end];
                if(v < minv) minv = v;
            }
            opt[end][set] = minv;
        }
        return opt[end][set];
    }
    let bestlen = 99999;  
    let N = (1 << (n-1))-1;
    for(let t = 0; t < n-1; t++){
        let s = solve(N,t);
        let len = s + dist[t][n-1];
        if(len < bestlen) bestlen = len;
    }

    return bestlen;
}

Solution

  • If the first node is node 0 and you want node 2 as your start node, then just interchange row 0 and row 2, and column 0 and column 2. Modify the adjacency matrix instead of modifying the algorithm.