1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| class Solution { public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
int waters1 = 0, waters2 = 0;
Map<Integer, Set<Integer>> visitedMap = new HashMap<>(); return dfs(visitedMap, waters1, waters2, jug1Capacity, jug2Capacity, targetCapacity); }
private boolean dfs(Map<Integer, Set<Integer>> visitedMap, int waters1, int waters2, int jug1Capacity, int jug2Capacity, int targetCapacity) { if (waters1 + waters2 == targetCapacity) { return true; }
if (visitedMap.getOrDefault(waters1, Collections.emptySet()).contains(waters2)) { return false; }
visitedMap.computeIfAbsent(waters1, k -> new HashSet<>()).add(waters2);
if (dfs(visitedMap, jug1Capacity, waters2, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } if (dfs(visitedMap, 0, waters2, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } if (dfs(visitedMap, waters1, jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } if (dfs(visitedMap, waters1, 0, jug1Capacity, jug2Capacity, targetCapacity)) { return true; }
int remain2 = jug2Capacity - waters2; if (waters1 >= remain2) { if (dfs(visitedMap, waters1 - remain2, jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } } else { if (dfs(visitedMap, 0, waters2 + waters1, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } }
int remain1 = jug1Capacity - waters1; if (waters2 >= remain1) { if (dfs(visitedMap, jug1Capacity, waters2 - remain1, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } } else { if (dfs(visitedMap, waters1 + waters2, 0, jug1Capacity, jug2Capacity, targetCapacity)) { return true; } }
return false; } }
|