-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path427.cpp
38 lines (36 loc) · 1.41 KB
/
427.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
private:
Node* dfs(vector<vector<int>>& grid, int x, int y, int length) {
if (length == 1) {
return new Node(grid[x][y] == 1, true, nullptr, nullptr, nullptr, nullptr);
}
int newLength = length / 2;
Node* topLeft = dfs(grid, x, y, newLength);
Node* topRight = dfs(grid, x, y + newLength, newLength);
Node* botLeft = dfs(grid, x + newLength, y, newLength);
Node* botRight = dfs(grid, x + newLength, y + newLength, newLength);
if (topLeft -> isLeaf && topRight -> isLeaf && botRight -> isLeaf && botLeft -> isLeaf &&
((topLeft -> val && topRight -> val && botLeft -> val && botRight -> val) ||
!(topLeft -> val || topRight -> val || botLeft -> val || botRight -> val))) {
bool val = topLeft -> val;
delete topLeft;
topLeft = nullptr;
delete topRight;
topRight = nullptr;
delete botLeft;
botLeft = nullptr;
delete botRight;
botRight = nullptr;
return new Node(val, true, nullptr, nullptr, nullptr, nullptr);
}
return new Node(true, false, topLeft, topRight, botLeft, botRight);
}
public:
Node* construct(vector<vector<int>>& grid) {
int N = grid.size();
if (N == 0) {
return nullptr;
}
return dfs(grid, 0, 0, N);
}
};