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
| import java.util.*;
class Solution { public boolean canMeasureWater(int x, int y, int z) { if (z == 0) { return true; } if (x + y < z) { return false; } Queue<Map.Entry<Integer, Integer>> queue = new ArrayDeque<>(); AbstractMap.SimpleEntry<Integer, Integer> start = new AbstractMap.SimpleEntry<>(0, 0); queue.add(start); Set<Map.Entry<Integer, Integer>> visited = new HashSet<>(); visited.add(start); while (!queue.isEmpty()) { Map.Entry<Integer, Integer> entry = queue.poll(); int curX = entry.getKey(); int curY = entry.getValue(); if (curX == z || curY == z || curX + curY == z) { return true; } if (curX == 0) { addIntoQueue(queue, visited, new AbstractMap.SimpleEntry<>(x, curY)); } if (curY == 0) { addIntoQueue(queue, visited, new AbstractMap.SimpleEntry<>(curX, y)); } if (curY < y) { addIntoQueue(queue, visited, new AbstractMap.SimpleEntry<>(0, curY)); } if (curX < x) { addIntoQueue(queue, visited, new AbstractMap.SimpleEntry<>(curX, 0)); }
int moveSize = Math.min(curX, y - curY); addIntoQueue(queue, visited, new AbstractMap.SimpleEntry<>(curX - moveSize, curY + moveSize)); moveSize = Math.min(curY, x - curX); addIntoQueue(queue, visited, new AbstractMap.SimpleEntry<>(curX + moveSize, curY - moveSize)); } return false; }
private void addIntoQueue(Queue<Map.Entry<Integer, Integer>> queue, Set<Map.Entry<Integer, Integer>> visited, Map.Entry<Integer, Integer> newEntry) { if (!visited.contains(newEntry)) { visited.add(newEntry); queue.add(newEntry); } } }
|