leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0427.cpp (1247B)


      1 class Solution {
      2   public:
      3     Node *construct(vector<vector<int>> &grid, int rowStart, int rowEnd, int colStart, int colEnd) {
      4         if (rowStart > rowEnd || colStart > colEnd) return nullptr;
      5 
      6         bool isLeaf = true;
      7         int val = grid[rowStart][colStart];
      8         for (int i = rowStart; i <= rowEnd; i++) {
      9             for (int j = colStart; j <= colEnd; j++) {
     10                 if (grid[i][j] != val) {
     11                     isLeaf = false;
     12                     break;
     13                 }
     14             }
     15             if (!isLeaf) break;
     16         }
     17 
     18         if (isLeaf) return new Node(val, true);
     19 
     20         int rowMid = (rowStart + rowEnd) / 2;
     21         int colMid = (colStart + colEnd) / 2;
     22         Node *topLeft = construct(grid, rowStart, rowMid, colStart, colMid);
     23         Node *topRight = construct(grid, rowStart, rowMid, colMid + 1, colEnd);
     24         Node *bottomLeft = construct(grid, rowMid + 1, rowEnd, colStart, colMid);
     25         Node *bottomRight = construct(grid, rowMid + 1, rowEnd, colMid + 1, colEnd);
     26         return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);
     27     }
     28     Node *construct(vector<vector<int>> &grid) {
     29         int n = grid.size();
     30         return construct(grid, 0, n - 1, 0, n - 1);
     31     }
     32 };