cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 128 of 218
Ideas this builds on
Extra state & 3D DP128 / 218

A visited set in a few bits

Picture

Give A, B, C bits 0, 1, 2. Visiting A lights 001; adding C produces 101. Visiting them in the reverse order produces the same number, because a mask represents a set, not a sequence.

Predict

How do you test whether place v is present without changing any other bit?

Walk through the small example

mask & (1 << v) is nonzero exactly when v’s bit is set. Use OR, not addition, to include an item idempotently.

Mental model and complete Python solution

1<<v isolates one switch. OR turns that switch on while preserving the others. AND checks it. The all-visited mask is (1<<n)−1, which has n low bits set. Including the same item twice with OR leaves the mask unchanged; addition could carry into another bit. This representation is useful only when item identity matters but earlier visiting order does not affect future choices.

What the function promises: Items use labels 0..n−1 for a small fixed n. The example converts between a set of labels and its integer mask.

def encode(items):
    mask = 0
    for item in items:
        if item < 0:
            raise ValueError("Bit positions must be nonnegative")
        mask |= 1 << item
    return mask

def decode(mask, n):
    return {item for item in range(n) if mask & (1 << item)}

assert encode([0, 2]) == 0b101
assert encode([2, 0, 2]) == 0b101
assert decode(0b101, 3) == {0, 2}
assert (1 << 3) - 1 == 0b111

Work and storage: With small masks fitting the usual machine-word model, encoding m labels costs O(m), and decoding n positions costs O(n). Python integers are arbitrary precision; very large masks have multiword bit-operation costs. More importantly, n items still admit 2^n different subsets.

When to recognize it: Give each item one on/off bit. Different visit orders with the same items create the same mask.

Check before applying it: One integer can encode many different subsets. There are still 2ⁿ masks, so the search can remain exponential.

Change one rule

The order of the last two visited nodes changes which moves are legal. Is the visited mask enough?

See what changes

No. Add the necessary recent-order information to the state or prove it can be derived. Compact encoding is not permission to drop information that changes the remaining problem.

Connect

sets: This is a set encoded differently, not less information.

Shortest Path Visiting All Nodes: Pair the visited mask with the current node.