Given two jugs with the maximum capacity of m and n liters respectively. The jugs don’t have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or (d, 0).
Input: 4 3 2
Output: (0, 0) –> (4, 0) –> (4, 3) –> (0, 3) –> (3, 0) –> (3, 3) –> (4, 2) –> (0, 2)
Input: 5 2 4
Output: (0, 0) –> (5, 0) –> (5, 2) –> (0, 2) –> (2, 0) –> (2, 2) –> (4, 0)
Approach: An approach using BFS has been discussed in the previous post. In this post an approach using memoization and recursion has been discussed. At any point, there can be a total of six possibilities:
- Empty the first jug completely
- Empty the second jug completely
- Fill the first jug
- Fill the second jug
- Fill the water from the second jug into the first jug until the first jug is full or the second jug has no water left
- Fill the water from the first jug into the second jug until the second jug is full or the first jug has no water left
Approach: Using Recursion, visit all the six possible moves one by one until one of them returns True. Since there can be repetitions of same recursive calls, hence every return value is stored using memoization to avoid calling the recursive function again and returning the stored value.
Below is the implementation of the above approach:
Steps: 0 0 4 0 4 3 0 3 3 0 3 3 4 2 0 2
Time complexity: O(M * N)
Auxiliary Space: O(M * N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- The Two Water Jug Puzzle
- Edit Distance | DP using Memoization
- Longest Common Subsequence | DP using Memoization
- Memoization using decorators in Python
- Tabulation vs Memoization
- Memoization (1D, 2D and 3D)
- Program to find amount of water in a given glass
- Word Break Problem using Backtracking
- Josephus problem | Set 1 (A O(n) Solution)
- Word Wrap Problem | DP-19
- Box Stacking Problem | DP-22
- Largest Independent Set Problem | DP-26
- Word Break Problem | DP-32
- Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
- Mobile Numeric Keypad Problem
- Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
- Dynamic Programming | High-effort vs. Low-effort Tasks Problem
- A Space Optimized DP solution for 0-1 Knapsack Problem
- Friends Pairing Problem
- Gold Mine Problem
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.