-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
67 lines (62 loc) · 1.75 KB
/
Solution.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
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 dfs(0, 0, grid.size() - 1, grid[0].size() - 1, grid);
}
Node* dfs(int a, int b, int c, int d, vector<vector<int>>& grid) {
int zero = 0, one = 0;
for (int i = a; i <= c; ++i) {
for (int j = b; j <= d; ++j) {
if (grid[i][j])
one = 1;
else
zero = 1;
}
}
bool isLeaf = zero + one == 1;
bool val = isLeaf && one;
Node* node = new Node(val, isLeaf);
if (isLeaf) return node;
node->topLeft = dfs(a, b, (a + c) / 2, (b + d) / 2, grid);
node->topRight = dfs(a, (b + d) / 2 + 1, (a + c) / 2, d, grid);
node->bottomLeft = dfs((a + c) / 2 + 1, b, c, (b + d) / 2, grid);
node->bottomRight = dfs((a + c) / 2 + 1, (b + d) / 2 + 1, c, d, grid);
return node;
}
};