-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct-quad-tree.cpp
More file actions
72 lines (63 loc) · 1.86 KB
/
construct-quad-tree.cpp
File metadata and controls
72 lines (63 loc) · 1.86 KB
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
68
69
70
71
72
//
// Created by Chenguang Wang on 2024/2/22.
//
class Node {
public:
bool val;
bool isLeaf;
Node *topLeft;
Node *topRight;
Node *bottomLeft;
Node *bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = nullptr;
topRight = nullptr;
bottomLeft = nullptr;
bottomRight = nullptr;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = nullptr;
topRight = nullptr;
bottomLeft = nullptr;
bottomRight = nullptr;
}
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;
}
};
#include <vector>
#include <functional>
using namespace std;
class Solution {
public:
Node *construct(vector<vector<int>> &grid) {
function < Node * (int, int, int, int) > dfs = [&](int r0, int c0, int r1, int c1) {
for (int i = r0; i < r1; ++i) {
for (int j = c0; j < c1; ++j) {
if (grid[i][j] != grid[r0][c0]) { // 不是叶节点
return new Node(
true,
false,
dfs(r0, c0, (r0 + r1) / 2, (c0 + c1) / 2),
dfs(r0, (c0 + c1) / 2, (r0 + r1) / 2, c1),
dfs((r0 + r1) / 2, c0, r1, (c0 + c1) / 2),
dfs((r0 + r1) / 2, (c0 + c1) / 2, r1, c1)
);
}
}
}
// 是叶节点
return new Node(grid[r0][c0], true);
};
return dfs(0, 0, grid.size(), grid.size());
}
};