Solution.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package _365;
  2. import java.util.HashSet;
  3. /**
  4. * Error: StackOverFlow!!!
  5. */
  6. class OldSolution {
  7. public boolean canMeasureWater(int x, int y, int z) {
  8. HashSet<String> set = new HashSet<>();
  9. return canMeasureWaterIter(x, y, z, 0, 0, set);
  10. }
  11. /**
  12. * @param _x The water in bottle x
  13. * @param _y The water in bottle y
  14. * @param set The set of old states
  15. */
  16. private boolean canMeasureWaterIter(int x, int y, int z, int _x, int _y, HashSet<String> set) {
  17. boolean isDone = _x == z || _y == z || (_x + _y) == z;
  18. if (isDone)
  19. return true;
  20. boolean isTried = set.contains(_x + ":" + _y);
  21. if (isTried)
  22. return false;
  23. set.add(_x + ":" + _y);
  24. int _x_x2y, _y_x2y, _x_y2x, _y_y2x;
  25. int sum_xy = _x + _y;
  26. if (sum_xy > x) {
  27. _x_x2y = x;
  28. _y_x2y = sum_xy - x;
  29. } else {
  30. _x_x2y = sum_xy;
  31. _y_x2y = 0;
  32. }
  33. if (sum_xy > y) {
  34. _y_y2x = y;
  35. _x_y2x = sum_xy - y;
  36. } else {
  37. _y_y2x = sum_xy;
  38. _x_y2x = 0;
  39. }
  40. return canMeasureWaterIter(x, y, z, x, _y, set) || canMeasureWaterIter(x, y, z, _x, y, set)
  41. || canMeasureWaterIter(x, y, z, 0, _y, set) || canMeasureWaterIter(x, y, z, _x, 0, set)
  42. || canMeasureWaterIter(x, y, z, _x_x2y, _y_x2y, set) || canMeasureWaterIter(x, y, z, _x_y2x, _y_y2x, set);
  43. }
  44. private static void testCanMeasureWater(int x, int y, int z) {
  45. OldSolution solution = new OldSolution();
  46. System.out.println(solution.canMeasureWater(x, y, z));
  47. }
  48. public static void main(String[] args) {
  49. testCanMeasureWater(3, 5, 4);
  50. testCanMeasureWater(2, 6, 5);
  51. }
  52. }