Algorithm Atlas · worked example
See the algorithm, step by step
Encode the chosen subset in bits and transition by adding one unused item.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
matrix=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 28fn travelling_salesman(cost: &[Vec<i32>]) -> i32 {
let n = cost.len();
assert!(n > 0 && n <= 16);
let states = 1 << n;
let infinity = i32::MAX / 4;
let mut dp = vec![vec![infinity; n]; states];
dp[1][0] = 0;
for mask in 1..states {
for last in 0..n {
if dp[mask][last] == infinity {
continue;
}
for next in 0..n {
if mask >> next & 1 == 0 {
let new = mask | 1 << next;
dp[new][next] = dp[new][next].min(dp[mask][last] + cost[last][next]);
}
}
}
}
(0..n)
.map(|last| dp[states - 1][last] + cost[last][0])
.min()
.unwrap()
}
fn main() {
let result = travelling_salesman(&[
vec![0, 10, 15, 20],
vec![10, 0, 35, 25],
vec![15, 35, 0, 30],
vec![20, 25, 30, 0],
])
.to_string();
println!("{result}");
}
Try your own version
Compare the visible input `matrix=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]` with `matrix=[[0,1,5],[1,0,2],[5,2,0]]`. Predict why their results are `80` and `8`. Then change one legal value and explain whether the same invariant, the visited vertex subset and current final vertex, still applies.
Open personal copy in Playground ↗Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.
Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Understand it
In the four-city sample, a minimum closed tour costs 80. State (mask,last) records the cheapest route starting at 0, visiting exactly mask and ending at last. Add the edge back to 0 only after all vertices have been visited.
The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Return minimum tour cost starting and ending at 0. The visible fixture is matrix=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] and its example result is 80. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.
Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.
String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
A problem is a good match for Bitmask DP when it asks for small assignment, travelling salesperson, pairing. Here the concrete task is: Return minimum tour cost starting and ending at 0. The visible input matrix=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Write the dependency arrows before choosing loop order; a recurrence that reads the future cannot be filled left to right without adjustment. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Encode the chosen subset in bits and transition by adding one unused item. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A multidimensional or structured DP state records the information needed to identify a subproblem: two prefixes, an interval, a bitmask, a tree node, or a resource limit. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.
Compare costs before committing. The advertised bound is O(2^n * n^2) typical · O(2^n*n) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 80 and explain which part of the state lets the method reach that result.
When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test base states, boundary cells or subsets, ties, and whether a compressed representation overwrites a value still needed later. Index tables consistently where the state is tabular. Compress dimensions only after the full recurrence and its dependency order are clear. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.
The pattern
Encode the chosen subset in bits and transition by adding one unused item.
When to use it: small assignment, travelling salesperson, pairing
Complexity: O(2^n * n^2) typical · O(2^n*n) space
Input: matrix=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]
Read the code
fn travelling_salesman(cost: &[Vec<i32>]) -> i32 {
let n = cost.len();
assert!(n > 0 && n <= 16);
let states = 1 << n;
let infinity = i32::MAX / 4;
let mut dp = vec![vec![infinity; n]; states];
dp[1][0] = 0;
for mask in 1..states {
for last in 0..n {
if dp[mask][last] == infinity {
continue;
}
for next in 0..n {
if mask >> next & 1 == 0 {
let new = mask | 1 << next;
dp[new][next] = dp[new][next].min(dp[mask][last] + cost[last][next]);
}
}
}
}
(0..n)
.map(|last| dp[states - 1][last] + cost[last][0])
.min()
.unwrap()
}
fn main() {
let result = travelling_salesman(&[
vec![0, 10, 15, 20],
vec![10, 0, 35, 25],
vec![15, 35, 0, 30],
vec![20, 25, 30, 0],
])
.to_string();
println!("{result}");
}
Complete std-only bitmask-dp program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Try it
Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.
What success looks like: You can justify the choice from constraints rather than from a remembered problem title.
Check your understanding
Trace Bitmask DP on input matrix=[[0,5],[5,0]]. Which result follows from the documented contract?
Reveal the answer
11109
For this input the result is 10. The visited vertex subset and current final vertex. Compare this independent fixture with the worked trace: In the four-city sample, a minimum closed tour costs 80. State (mask,last) records the cheapest route starting at 0, visiting exactly mask and ending at last. Add the edge back to 0 only after all vertices have been visited.
Go deeper
Common misconception: “Only the number of visited vertices”
The visited vertex subset and current final vertex. In the four-city sample, a minimum closed tour costs 80. State (mask,last) records the cheapest route starting at 0, visiting exactly mask and ending at last. Add the edge back to 0 only after all vertices have been visited.
- Concrete transition: In the four-city sample, a minimum closed tour costs 80. State (mask,last) records the cheapest route starting at 0, visiting exactly mask and ending at last. Add the edge back to 0 only after all vertices have been visited.
- Independent second fixture: Input
matrix=[[0,5],[5,0]]produces10. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation. - Boundary and contract: Input
matrix=[[0,3,4],[3,0,1],[4,1,0]]produces8. The visited vertex subset and current final vertex. The stated work bound is O(2^n * n^2) typical · O(2^n*n) space. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input matrix=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] with matrix=[[0,1,5],[1,0,2],[5,2,0]]. Predict why their results are 80 and 8. Then change one legal value and explain whether the same invariant, the visited vertex subset and current final vertex, still applies.
Connections
- Bitmask DP: Mental Model: Encode the chosen subset in bits and transition by adding one unused item.
- Challenge: Bitmask DP: Return minimum tour cost starting and ending at 0.
Reveal the Algorithm Atlas answer
80
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Bitmask DP: When to Use It (courseId "algorithms", lessonId "algorithm.bitmask-dp.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.bitmask-dp.recognize Goal: The visited vertex subset and current final vertex. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.bitmask-dp.recognize) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.