Guest User

Untitled

a guest
Jan 27th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. /*
  2. // Definition for a QuadTree node.
  3. class Node {
  4. public:
  5.     bool val;
  6.     bool isLeaf;
  7.     Node* topLeft;
  8.     Node* topRight;
  9.     Node* bottomLeft;
  10.     Node* bottomRight;
  11.  
  12.     Node() {}
  13.  
  14.     Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
  15.         val = _val;
  16.         isLeaf = _isLeaf;
  17.         topLeft = _topLeft;
  18.         topRight = _topRight;
  19.         bottomLeft = _bottomLeft;
  20.         bottomRight = _bottomRight;
  21.     }
  22. };
  23. */
  24. class Solution {
  25. public:
  26.     Node* buildLeaf(bool b) {
  27.         return new Node(b, true, nullptr, nullptr, nullptr, nullptr);
  28.     }
  29.     Node* buildNode() {
  30.         return new Node(false, false, nullptr, nullptr, nullptr, nullptr);
  31.     }
  32.     Node* run(const vector<vector<int>>& g, int si, int sj, int n) {
  33.         if (n==1) return buildLeaf(g[si][sj]);
  34.         else {
  35.             Node* ret = buildNode();
  36.             Node* Node::* chi[4] = {
  37.                 &Node::topLeft,
  38.                 &Node::topRight,
  39.                 &Node::bottomLeft,
  40.                 &Node::bottomRight
  41.             };
  42.             const int ii[] = {0, 0, 1, 1};
  43.             const int jj[] = {0, 1, 0, 1};
  44.             for (int k=0; k<4; k++) {
  45.                 const int nn = n/2;
  46.                 ret->*chi[k] = run(g, si+ii[k]*nn, sj+jj[k]*nn, nn);
  47.             }
  48.             if (all_of(chi, chi+4, [ret](auto x){return (ret->*x)->isLeaf;})) {
  49.                 if (count_if(chi, chi+4, [ret](auto x){return (ret->*x)->val;})%4!=0)
  50.                     return ret;
  51.                 ret->isLeaf = true;
  52.                 ret->val = (ret->*chi[0])->val;
  53.                 for (auto x : chi) {
  54.                     delete (ret->*x);
  55.                     ret->*x = nullptr;
  56.                 }
  57.             }
  58.             return ret;
  59.         }
  60.     }
  61.     Node* construct(vector<vector<int>>& grid) {
  62.         const int n = grid.size();
  63.         return run(grid, 0, 0, n);
  64.     }
  65. };
Advertisement
Add Comment
Please, Sign In to add comment