#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Home / Blog /

Water Jug Problem with Heuristic Search

Solving Classic AI Challenges

Published
6 min read
Scroll Down

The water jug problem

You have a 4-litre jug and a 3-litre jug. Neither has any markings. There is a tap to fill them and a drain to empty them. How do you get exactly 2 litres in the 4-litre jug?

The puzzle is a standard example in AI textbooks (Rich and Knight's Artificial Intelligence uses it to introduce state spaces and production rules) because it is small enough to solve by hand but still needs a systematic search.

State space representation

  • State: an ordered pair (x, y), where x is the water in the 4-litre jug (0 to 4) and y is the water in the 3-litre jug (0 to 3).
  • Start state: (0, 0), both jugs empty.
  • Goal states: (2, n) for any n, that is, 2 litres in the 4-litre jug.
  • Operators: fill a jug, empty a jug, or pour one jug into the other until the source is empty or the destination is full.

There are 4 × 5 = 20 possible pairs, but only 14 states are reachable from (0, 0): every reachable state has at least one jug completely full or completely empty, because no operator can stop pouring halfway.

Production rules

RuleConditionFrom → ToMeaning
1x < 4(x, y) → (4, y)Fill the 4-litre jug
2y < 3(x, y) → (x, 3)Fill the 3-litre jug
3x > 0(x, y) → (0, y)Empty the 4-litre jug
4y > 0(x, y) → (x, 0)Empty the 3-litre jug
5x + y ≥ 4, y > 0(x, y) → (4, y − (4 − x))Pour from 3L into 4L until 4L is full
6x + y ≥ 3, x > 0(x, y) → (x − (3 − y), 3)Pour from 4L into 3L until 3L is full
7x + y ≤ 4, y > 0(x, y) → (x + y, 0)Pour all of 3L into 4L
8x + y ≤ 3, x > 0(x, y) → (0, x + y)Pour all of 4L into 3L

A set of rules like this, plus a control strategy that decides which rule to apply next, is a production system. The control strategy is where search comes in.

Two shortest solutions (6 moves each)

MoveSolution 1: start by filling the 4L jugSolution 2: start by filling the 3L jug
1Fill 4L → (4, 0)Fill 3L → (0, 3)
2Pour 4L into 3L → (1, 3)Pour 3L into 4L → (3, 0)
3Empty 3L → (1, 0)Fill 3L → (3, 3)
4Pour 4L into 3L → (0, 1)Pour 3L into 4L until full → (4, 2)
5Fill 4L → (4, 1)Empty 4L → (0, 2)
6Pour 4L into 3L until full → (2, 3)Pour 3L into 4L → (2, 0)

Both reach the goal in 6 moves, and breadth-first search confirms that no 5-move solution exists. Which one a search finds depends only on the order in which it tries the rules.

Solving it with search in Python

The program generates successors with the six physical moves (rules 5–8 above collapse into two "pour until one side stops" moves), then solves the puzzle three ways: breadth-first search, A* and greedy best-first search. Each search keeps a record of states already seen, so it cannot loop between (0, 0) and (4, 0).

import heapq
from collections import deque

CAP_X, CAP_Y, TARGET = 4, 3, 2          # 4-litre jug x, 3-litre jug y, want 2 litres in x

def successors(state):
    x, y = state
    moves = [
        ("Fill 4L jug",          (CAP_X, y)),
        ("Fill 3L jug",          (x, CAP_Y)),
        ("Empty 4L jug",         (0, y)),
        ("Empty 3L jug",         (x, 0)),
        ("Pour 3L into 4L",      (min(CAP_X, x + y), y - (min(CAP_X, x + y) - x))),
        ("Pour 4L into 3L",      (x - (min(CAP_Y, x + y) - y), min(CAP_Y, x + y))),
    ]
    return [(name, s) for name, s in moves if s != state]   # drop moves that change nothing

def is_goal(state):
    return state[0] == TARGET

def rebuild(parent, state):
    steps = []
    while parent[state] is not None:
        prev, move = parent[state]
        steps.append((move, state))
        state = prev
    return steps[::-1]

def bfs(start=(0, 0)):
    parent, queue, expanded = {start: None}, deque([start]), 0
    while queue:
        state = queue.popleft()
        expanded += 1
        if is_goal(state):
            return rebuild(parent, state), expanded
        for move, nxt in successors(state):
            if nxt not in parent:
                parent[nxt] = (state, move)
                queue.append(nxt)

def best_first(h, start=(0, 0), use_g=True):
    """A* when use_g is True, greedy best-first search when it is False."""
    parent, g = {start: None}, {start: 0}
    heap, closed, expanded, tie = [(h(start), 0, start)], set(), 0, 0
    while heap:
        _, _, state = heapq.heappop(heap)
        if state in closed:
            continue
        closed.add(state)
        expanded += 1
        if is_goal(state):
            return rebuild(parent, state), expanded
        for move, nxt in successors(state):
            new_g = g[state] + 1
            if nxt not in g or new_g < g[nxt]:
                g[nxt], parent[nxt] = new_g, (state, move)
                tie += 1
                heapq.heappush(heap, ((new_g if use_g else 0) + h(nxt), tie, nxt))

path, n = bfs()
print(f"BFS: {len(path)} moves, {n} states expanded")
for move, state in path:
    print(f"  {move:<16} -> {state}")

h_admissible = lambda s: 0 if s[0] == TARGET else 1
h_distance = lambda s: abs(s[0] - TARGET)
for name, h, use_g in [("A*, h = 0/1", h_admissible, True),
                       ("A*, h = |x - 2|", h_distance, True),
                       ("Greedy, h = |x - 2|", h_distance, False)]:
    path, n = best_first(h, use_g=use_g)
    print(f"{name:<20}: {len(path)} moves, {n} states expanded, ends at {path[-1][1]}")

Output:

BFS: 6 moves, 13 states expanded
  Fill 4L jug      -> (4, 0)
  Pour 4L into 3L  -> (1, 3)
  Empty 3L jug     -> (1, 0)
  Pour 4L into 3L  -> (0, 1)
  Fill 4L jug      -> (4, 1)
  Pour 4L into 3L  -> (2, 3)
A*, h = 0/1         : 6 moves, 13 states expanded, ends at (2, 3)
A*, h = |x - 2|     : 6 moves, 12 states expanded, ends at (2, 3)
Greedy, h = |x - 2| : 6 moves, 12 states expanded, ends at (2, 3)

Choosing a heuristic for the water jug problem

A natural-looking heuristic is h(x, y) = |x − 2|, the distance of the 4-litre jug from the target. It does guide the search (12 states expanded instead of 13), but it is not admissible: from (4, 1), a single pour reaches (2, 3), yet h(4, 1) = 2. A heuristic that overestimates removes A*'s promise of an optimal answer. Here A* still found a 6-move solution, but that is a property of this tiny state space, not of the heuristic.

An admissible alternative is h = 0 at a goal and 1 everywhere else: no non-goal state can be solved in fewer than one move. It is safe but weak, so A* behaves almost exactly like BFS. This is the honest lesson of the puzzle: with only 14 reachable states and unit move costs, plain BFS is already optimal and fast, and heuristics matter far more in large spaces such as route finding or the 8-puzzle. For the theory behind admissible heuristics, see the A* algorithm.

What about hill climbing?

Hill climbing with h = |x − 2| starts at (0, 0) with h = 2. Every neighbour, (4, 0) and (0, 3), also has h = 2 or worse (|4 − 2| = 2, |0 − 2| = 2), so the very first step is a plateau and pure hill climbing stops without moving. Solving the puzzle needs moves that temporarily look no better, which is the classic weakness covered in search strategies and hill climbing.

When is a water jug puzzle solvable?

With jugs of capacity a and b, you can measure exactly c litres in one of the jugs if and only if c is a multiple of gcd(a, b) and c ≤ max(a, b). For 4 and 3, gcd = 1, so any amount from 0 to 4 litres is possible. For jugs of 6 and 4 litres, gcd = 2, so 3 litres can never be measured however you pour. Checking this first saves running a search that cannot succeed.

The water jug problem is usually solved first with BFS and DFS, and its repeated states (fill, empty, fill again) are a good illustration of why DFS needs a visited set. State-space search is part of the problem-solving module in Uncodemy's Artificial Intelligence course.