558.quad-tree-intersection.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. // Definition for a QuadTree node.
  3. class Node {
  4. public boolean val;
  5. public boolean isLeaf;
  6. public Node topLeft;
  7. public Node topRight;
  8. public Node bottomLeft;
  9. public Node bottomRight;
  10. public Node() {}
  11. public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
  12. val = _val;
  13. isLeaf = _isLeaf;
  14. topLeft = _topLeft;
  15. topRight = _topRight;
  16. bottomLeft = _bottomLeft;
  17. bottomRight = _bottomRight;
  18. }
  19. };
  20. */
  21. class Solution {
  22. public Node intersect(Node q1, Node q2) {
  23. if (q1.isLeaf) return (q1.val ? q1 : q2);
  24. if (q2.isLeaf) return (q2.val ? q2 : q1);
  25. q1.topLeft = intersect(q1.topLeft, q2.topLeft);
  26. q1.topRight = intersect(q1.topRight, q2.topRight);
  27. q1.bottomLeft = intersect(q1.bottomLeft, q2.bottomLeft);
  28. q1.bottomRight = intersect(q1.bottomRight, q2.bottomRight);
  29. if (q1.topLeft.isLeaf && q1.topRight.isLeaf && q1.bottomLeft.isLeaf && q1.bottomRight.isLeaf) {
  30. if (q1.topLeft.val && q1.topRight.val && q1.bottomLeft.val && q1.bottomRight.val) {
  31. q1.isLeaf = true;
  32. q1.val = true;
  33. return q1;
  34. }
  35. if (!(q1.topLeft.val || q1.topRight.val || q1.bottomLeft.val || q1.bottomRight.val)) {
  36. q1.isLeaf = true;
  37. q1.val = false;
  38. return q1;
  39. }
  40. }
  41. return q1;
  42. }
  43. }