DryRun
AlgorithmsCourseCompare
DryRun
AlgorithmsCourseCompareGitHubLinkedIn

© 2026 DryRun. Built by Aditya Pandey.

AlgorithmsAdvancedTravelling Salesperson (Branch and Bound)
Advancedadvancedbranch-and-boundtspgraph-optimization

Travelling Salesperson (Branch and Bound)

Branch and Bound for TSP explores partial tours and computes lower bounds on final cost. Partial paths that cannot beat the best complete tour found so far are pruned.

Complexity

Best
O(n!)
Average
O(n!)
Worst
O(n!)
Space
O(n)

Implementation

int tspBB(vector<vector<int>>& cost) {
    int n = cost.size(), best = INT_MAX;
    vector<bool> used(n, false);
    used[0] = true;
    function<void(int,int,int)> dfs = [&](int u, int cnt, int curr) {
        if (cnt == n) {
            if (cost[u][0]) best = min(best, curr + cost[u][0]);
            return;
        }
        if (curr >= best) return;
        for (int v = 0; v < n; v++) {
            if (!used[v] && cost[u][v]) {
                used[v] = true;
                dfs(v, cnt + 1, curr + cost[u][v]);
                used[v] = false;
            }
        }
    };
    dfs(0, 1, 0);
    return best;
}

How It Works

1.State Space

Nodes represent partial tours; depth equals number of visited cities.

2.Bounding

Lower/upper bounds cut large parts of permutation tree.

3.Guarantee

Search remains exact; pruning only removes provably suboptimal branches.

Related Algorithms

LayoutGridTravelling Salesperson (DP / Held-Karp)CornerUpLeftHamiltonian Cycle

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms