Water Pouring Problem - Graph Modelling
We have three containers whose sizes are 10 litres,7 litres, and 4 litres,respectively. The 7-litre and 4-litre containers start out full of water, but the 10-litre container is initially empty. We are allowed one type of operation: pouring the contents of one container into another,stopping only when the source container is empty or the destination container is full.We want to know if there is a sequence of pourings that leaves exactly 2litres in the 7 or 4-litre container. Model this as a graph problem and solve.
Problem Summary:
We have three containers:
-
A → 10 liters (capacity)
-
B → 7 liters (capacity)
-
C → 4 liters (capacity)
Initially:
-
A = 0 liters (empty)
-
B = 7 liters (full)
-
C = 4 liters (full)
Operation allowed:
Goal:
How to model this as a graph problem?
-
Each state is a node in the graph.
A state is represented as a triplet(A, B, C)
. -
An edge between two states represents a pouring operation (pour from one container to another).
-
Start node: (0, 7, 4)
-
Goal node: any node where B==2 or C==2.
-
Graph traversal: use BFS (Breadth-First Search) to find the shortest sequence of pourings to reach the goal.
Graph Search Algorithm:
1. Define State:
2. Valid operations (edges):
For every state, you can try:
-
Pour A → B
-
Pour A → C
-
Pour B → A
-
Pour B → C
-
Pour C → A
-
Pour C → B
Apply the pouring operation according to container limits.
3. BFS Steps:
-
Start from initial state (0,7,4)
-
At each step, generate all possible next states
-
Push them into the queue
-
Keep track of visited states to avoid cycles
-
If you reach a state with 2 liters in B or C, STOP — print the path.
Pseudocode:
Full Explanation:
Imagine each state as a node:
-
Each pouring moves to a new node.
-
BFS ensures you find the shortest sequence (minimum number of pourings).
-
Visited table (3D array) is important:
visited[A][B][C] = 1
means already explored
Comments
Post a Comment