Water Jug problem using BFS
Pattern: Shortest paths
A state is how much water is in each jug. From a state you can fill a jug, empty a jug, or pour one into the other until one is full or empty. BFS over states from (0, 0) finds the fewest operations to have d litres in either jug.
The problem
Given jugs of m and n litres (both start empty) and a target d, return the fewest operations (fill a jug, empty a
jug, pour one into the other) to have exactly d litres in one of the jugs, or -1 if it is impossible.
Think first
- What is a state?
- How many moves does each state have?
- When is the target impossible?
Hints
Brute force, and why it fails
Try sequences of operations of growing length: exponential.
The key insight
There are only (m + 1) × (n + 1) states, so BFS over them finds the minimum quickly.
Dry run
| steps | 2 |
|---|
Jugs of 3 and 5 litres, target 4. Fill 5: (0, 5). Pour into 3: (3, 2).
Step 1 of 3
The plan
BFS from (0, 0) over the six moves; stop when either jug holds d
Complexity
- Time
O(m × n)- Space
O(m × n)
Each state once.
Edge cases
- d = 0: 0 operations.
- d larger than both jugs: -1.
- d equal to a jug: 1.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int minSteps(int m, int n, int d) {
int[][] dist = new int[m + 1][n + 1]; // a state is how much is in each jug
for (int[] row : dist) Arrays.fill(row, -1);
dist[0][0] = 0;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[]{0, 0});
while (!q.isEmpty()) { // each operation is one step: BFS over states
int[] s = q.poll();
int a = s[0], b = s[1];
if (a == d || b == d) return dist[a][b];
int p1 = Math.min(a, n - b), p2 = Math.min(b, m - a);
int[][] next = {{m, b}, {a, n}, {0, b}, {a, 0}, {a - p1, b + p1}, {a + p2, b - p2}}; // fill, empty, pour
for (int[] t : next) if (dist[t[0]][t[1]] == -1) { dist[t[0]][t[1]] = dist[a][b] + 1; q.add(t); }
}
return -1;
}
}C++
class Solution {
public:
int minSteps(int m, int n, int d) {
vector<vector<int>> dist(m + 1, vector<int>(n + 1, -1)); // a state is how much is in each jug
dist[0][0] = 0;
queue<pair<int, int>> q;
q.push(make_pair(0, 0));
while (!q.empty()) { // each operation is one step: BFS over states
int a = q.front().first, b = q.front().second;
q.pop();
if (a == d || b == d) return dist[a][b];
int p1 = min(a, n - b), p2 = min(b, m - a);
int next[6][2] = {{m, b}, {a, n}, {0, b}, {a, 0}, {a - p1, b + p1}, {a + p2, b - p2}}; // fill, empty, pour
for (int k = 0; k < 6; k++) {
int x = next[k][0], y = next[k][1];
if (dist[x][y] == -1) { dist[x][y] = dist[a][b] + 1; q.push(make_pair(x, y)); }
}
}
return -1;
}
};Python
from collections import deque
class Solution:
def minSteps(self, m: int, n: int, d: int) -> int:
dist = {(0, 0): 0} # a state is how much is in each jug
q = deque([(0, 0)])
while q: # each operation is one step: BFS over states
a, b = q.popleft()
if a == d or b == d:
return dist[(a, b)]
p1, p2 = min(a, n - b), min(b, m - a)
for s in ((m, b), (a, n), (0, b), (a, 0), (a - p1, b + p1), (a + p2, b - p2)): # fill, empty, pour
if s not in dist:
dist[s] = dist[(a, b)] + 1
q.append(s)
return -1Common mistakes
- Pouring more than fits.
- Forgetting the empty moves.