Modeling Classic Puzzles: River Crossing, Jugs, and Proofs
Trees & GraphsModel answerLast updated
Turn a set of contest-style logic puzzles, led by the fox-chicken-grain river crossing, into formal models, and give algorithms with proofs of correctness and optimality.
You are given a set of short, contest-style logic puzzles (roughly middle-school competition level). For each one, you must produce a method and a justification, not just a final number.
The headline puzzle:
A farmer must carry a fox, a chicken, and a sack of grain across a river. The boat holds the farmer plus at most one item. If the farmer is not present on a bank, then:
- the fox and the chicken cannot be there together, and
- the chicken and the grain cannot be there together.
Tasks
- Formalize the river crossing as a search problem. Define the state, the legal moves, which states are safe, and the goal.
- Give an algorithm that finds the fewest crossings and returns the sequence of moves. State its time and space complexity, including a generalization to n items with an arbitrary list of conflicting pairs.
- Prove that the algorithm is correct (sound, complete, optimal). Also give a short human-style argument for why the minimum is 7 crossings.
- Explain how you would approach other puzzles of this style. For each family below, name the technique and sketch the proof:
- Measuring 4 L with a 3 L jug and a 5 L jug.
- Tiling an 8×8 board with two opposite corners removed using dominoes.
- Reaching all-heads by repeatedly flipping coins under some rule.
- Drawing socks of 3 colors to guarantee a matching pair.
- A game where players alternately take 1 to 3 stones and the player taking the last stone wins.
- Finding one heavier coin among 9 using a balance scale.
State your assumptions and cover edge cases such as unsolvable instances.
Hints
Hint 1
Encode the river crossing as a tuple of four bits (farmer, fox, chicken, grain), each recording which bank the entity is on. Only 16 states exist, and several are unsafe.
Hint 2
Every crossing costs one unit, so a breadth-first search from the all-start-bank state to the all-far-bank state gives the shortest path. Store a parent pointer per state to rebuild the moves.
Hint 3
For the other puzzles, ask which tool fits: an invariant or coloring argument for impossibility, parity for toggling, pigeonhole for worst-case guarantees, backward induction for take-away games, and counting outcomes for weighing problems.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
The expected answer has three layers: a formal model, an algorithm, and a proof. A bare answer such as "7 moves" earns little. Show how you get there and why nothing shorter exists.
River crossing as a graph search
State. A tuple (farmer, fox, chicken, grain), each entry 0 (starting bank) or 1 (far bank). There are 2⁴ = 16 states.
Safe states. A state is unsafe if the farmer is on the opposite bank from a pair that conflicts: fox with chicken, or chicken with grain. Exactly 10 of the 16 states are safe.
Moves. The farmer always crosses, either alone or with one item currently on his bank. Keep only moves whose resulting state is safe.
Goal. Reach (1,1,1,1) from (0,0,0,0).
Algorithm. Breadth-first search with a visited/parent map. Every edge has cost 1, so BFS gives the minimum number of crossings.
from collections import deque
NAMES = ("farmer", "fox", "chicken", "grain")
def is_safe(s):
f, fox, ch, gr = s
if fox == ch != f:
return False
if ch == gr != f:
return False
return True
def solve():
start, goal = (0, 0, 0, 0), (1, 1, 1, 1)
parent = {start: None}
q = deque([start])
while q:
s = q.popleft()
if s == goal:
break
f = s[0]
for item in (None, 1, 2, 3):
if item is not None and s[item] != f:
continue
n = list(s)
n[0] = 1 - f
if item is not None:
n[item] = 1 - f
n = tuple(n)
if is_safe(n) and n not in parent:
parent[n] = (s, "alone" if item is None else NAMES[item])
q.append(n)
if goal not in parent:
return None
path, s = [], goal
while parent[s] is not None:
s, m = parent[s]
path.append(m)
return path[::-1]
The result is chicken, alone, fox, chicken, grain, alone, chicken (7 crossings). Swapping the fox and grain steps gives a second optimal plan.
Correctness proof
- Soundness: only safe states are enqueued, and each edge is a legal boat trip, so any returned path is valid.
- Optimality: BFS dequeues states in non-decreasing distance order. The first time a state is discovered, it is via a shortest path. This holds for the goal as well.
- Completeness: the state space is finite and states are never revisited, so the search terminates. If the goal is never discovered, no solution exists.
Human argument for 7
- The first move is forced. Leaving alone lets the fox eat the chicken. Taking the fox leaves chicken with grain. Taking the grain leaves fox with chicken. So the chicken goes first.
- After the fox or grain crosses, it would be left with the chicken on the far bank, so the chicken must be brought back at some point.
- The chicken therefore crosses forward twice, plus the fox and the grain once each: 4 loaded forward trips. Between consecutive forward trips there is at least one return trip, giving at least 3 returns. Total at least 4 + 3 = 7.
Complexity and generalization
For n items and a conflict list C, there are 2ⁿ⁺¹ states, up to n + 1 moves each, and a safety check costing O(|C|). Time is O(2ⁿ · n · |C|), and space is O(2ⁿ). If the boat holds k items, enumerate subsets of up to k items on the farmer's bank. The BFS structure is unchanged.
Toolkit for the other puzzles
| Family | Puzzle | Technique and proof |
|---|---|---|
| State search | 4 L from 3 L and 5 L jugs | States (a, b); moves are fill, empty, pour; BFS gives the fewest steps. A target t is reachable only if gcd(3,5) divides t and t ≤ 5. |
| Invariant / coloring | Domino tiling with opposite corners removed | Each domino covers one black and one white square. The board is left with 32 of one color and 30 of the other, so no tiling exists. |
| Parity | Coin flips to all-heads | Find a quantity whose parity never changes under a move. If start and target differ in it, the target is unreachable. |
| Pigeonhole | Socks in 3 colors | Three draws can all differ, so 4 draws force a pair. Show tightness with the 3-draw counterexample. |
| Backward induction | Take 1 to 3 stones, last stone wins | Multiples of 4 are losing for the player to move. From 4k every move lands on a non-multiple. From any non-multiple, a move to a multiple of 4 exists. |
| Information counting | 1 heavy coin among 9, two weighings | Each weighing has 3 outcomes, so two weighings distinguish 3² = 9 cases. Split 3-3-3, then 1-1-1. The same counting gives the lower bound. |
Edge cases and assumptions
- Unsolvable instances. If conflicts make progress impossible, BFS exhausts the states and returns
Nonerather than looping. - No items. The answer is a single crossing.
- Unsafe start. State the assumption that the start is safe, or detect and report otherwise.
- Multiple optimal solutions. Say that BFS returns one of them, and that tie-breaking depends on move order.
Common mistakes
- Stating 7 without proving it cannot be done in fewer.
- Forgetting that moving an item back is allowed, which is the crucial step.
- Checking safety only for the destination bank and ignoring the bank the farmer just left.
- Claiming an impossibility without naming an invariant.
- Revisiting states without a visited set, causing infinite loops.
How to present it
Define the model first, state the algorithm and its complexity, prove correctness, then give a short human-readable argument. For the remaining puzzles, name the technique before computing anything, since that signals structured thinking.