1,题目要求
We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.
Each node has another two boolean attributes : isLeaf and val. isLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.
Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:
利用一个四叉树存储一个布尔网格。
2,题目思路
首先,对于一个N*N的矩阵,它可以表示一个布尔网格:即网格可以分为左上、右上、左下、右下四个部分。这四个部分可以是全1、全0、或者01混合。
而当我们将这样的网格划分到1*1的形式时,则网格就是非1即0的形式;我们也可以看到,只有全1或者全0或者这种1*1的小格子的形式,才会构成这个四叉树的叶子节点,否则就是普通的节点。
因此,对于这一题,我们可以利用递归的办法,首先对1*1的格子来进行节点的创立,如果对于一个4*4的是相同的数字(0或1),就将原先的这四个节点删除,然后用新的这个节点来进行代替叶子节点。
也就是说,依次地对这个网格进行二分,利用这种树中常用递归的办法实现整个算法的实现。
3,程序源码
//对于四叉树节点的定义
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 {
private:
Node* dfs(vector<vector<int>>& grid, int x, int y, int length) {
if (length == 1) { //遍历到了最后的1*1的网格,创建节点
return new Node(grid[x][y] == 1? true : false, true, nullptr, nullptr, nullptr, nullptr);
}
length /= 2;
//递归
auto topLeft = dfs(grid, x, y, length);
auto topRight = dfs(grid, x, y + length, length);
auto bottomLeft = dfs(grid, x + length, y, length);
auto bottomRight = dfs(grid, x + length, y + length, length);
//满足四个叶子节点的合并条件
if (topLeft->isLeaf && topRight->isLeaf && bottomLeft->isLeaf && bottomRight->isLeaf && topLeft->val == topRight->val && topRight->val == bottomLeft->val
&& bottomLeft->val == bottomRight->val) {
bool v = topLeft->val; //设置这个合并的新节点的值
delete topLeft; //删除原先的这四个节点
delete topRight;
delete bottomLeft;
delete bottomRight;
return new Node(v, true, nullptr, nullptr, nullptr, nullptr);
}
else {
auto p = new Node(true, false, nullptr, nullptr, nullptr, nullptr);
p->topLeft = topLeft;
p->topRight = topRight;
p->bottomLeft = bottomLeft;
p->bottomRight = bottomRight;
return p;
}
}
public:
Node* construct(vector<vector<int>>& grid) {
if (grid.size() == 0) {
return nullptr;
}
return dfs(grid, 0, 0, grid.size());
}
};