中级农民
- 积分
- 217
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-11-30
- 最后登录
- 1970-1-1
|
里口思儿其的代码
- /*
- // Definition for a QuadTree node.
- class Node {
- public:
- bool val;
- bool isLeaf;
- Node* topLeft;
- Node* topRight;
- Node* bottomLeft;
- Node* bottomRight;
- Node() {}
- Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
- val = _val;
- isLeaf = _isLeaf;
- topLeft = _topLeft;
- topRight = _topRight;
- bottomLeft = _bottomLeft;
- bottomRight = _bottomRight;
- }
- };
- */
- class Solution {
- public:
- Node* construct(vector<vector<int>>& grid) {
- return ConstructRec(grid, {0, 0}, {grid.size()-1, grid[0].size()-1} );
- }
-
- Node* ConstructRec(const vector<vector<int> > & grid, const pair<int, int>& topLeft, const pair<int, int>& bottomRight){
- Node* node = new Node();
- node->topLeft = NULL;
- node->topRight = NULL;
- node->bottomLeft = NULL;
- node->bottomRight = NULL;
- node->val = grid[topLeft.first][topLeft.second];
- if(!IsUniversal(grid, topLeft, bottomRight)){
- node->isLeaf = false;
- pair<int, int> center = {(topLeft.first + bottomRight.first) / 2, (topLeft.second + bottomRight.second) / 2};
- node->topLeft = ConstructRec(grid, topLeft, center);
- node->topRight = ConstructRec(grid, {topLeft.first, center.second+1}, {center.first, bottomRight.second});
- node->bottomLeft = ConstructRec(grid, {center.first+1, topLeft.second}, {bottomRight.first, center.second});
- node->bottomRight = ConstructRec(grid, {center.first+1, center.second+1}, bottomRight);
- }else node->isLeaf = true;
-
- return node;
-
- }
-
- bool IsUniversal(const vector<vector<int> > & grid,
- const pair<int, int>& topLeft, const pair<int, int>& bottomRight){
- int val = grid[topLeft.first][topLeft.second];
- for(int i = topLeft.first; i <= bottomRight.first; ++i){
- for(int j = topLeft.second; j <= bottomRight.second; ++j){
- if(val != grid[i][j]){
- return false;
- }
- }
- }
- return true;
- }
- };
复制代码 |
|