💧 Water Jug — 测水量
State-Space Search • Number Theory • Bezout's Identity
The water jug puzzle has circulated for centuries and became widely known to modern audiences through the 1995 action film Die Hard with a Vengeance, in which the protagonists must measure exactly 4 gallons using 5-gallon and 3-gallon jugs to defuse a bomb within minutes.
Despite its casual appearance, this puzzle rests on solid number theory. Bezout's Identity guarantees that for two integers a and b, every integer of the form ax + by is a multiple of gcd(a, b). Since gcd(5, 3) = 1 — which divides any integer, including 4 — measuring exactly 4 liters is mathematically guaranteed to be achievable. Had both jugs held an even number of liters, only even totals would be reachable, and measuring an odd amount would be impossible no matter how many steps you took.
This principle extends to all water jug puzzles: a target volume T is achievable with jugs of capacity a and b if and only if T is a multiple of gcd(a, b) and T ≤ max(a, b).
- You have one 5-liter jug and one 3-liter jug, both without measurement markings
- Three allowed operations: fill a jug completely from the tap; empty a jug completely; pour from one jug into the other until the source empties or the target is full
- Goal: end up with exactly 4 liters in one of the jugs
This puzzle is a textbook example of state-space search in computer science. Each pair (A liters in the 5L jug, B liters in the 3L jug) is a distinct state; each of the three operations is a directed edge in the state graph. There are at most 6 × 4 = 24 possible states, and Breadth-First Search (BFS) over this graph will always find the minimum-step solution.
Playing and solving this puzzle trains several important cognitive skills:
- Reverse thinking: working backward from the goal state to discover which prior state leads to it
- Exhaustive enumeration: systematically listing reachable states without double-counting
- Shortest-path intuition: understanding that "fewer steps" maps to BFS depth in a graph
- Problem modeling: the engineering habit of representing a physical problem as an abstract graph for algorithmic solution
Draw a table of all possible (5L-jug, 3L-jug) water-level pairs and trace where each of the three operations leads from every state. Starting at (0, 0), follow the chain of reachable states — somewhere in the network is a direct path to either (4, 0) or (?, 4) containing 4 liters. The shortest such path requires fewer than 10 steps.