Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2023-02-27 16:14:07
427. Construct Quad Tree
给你一个矩阵grid请用一个四元树来表示他,四元树的节点结构如下所示:
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
val: 表示这个区块的值,true = 1 false = 0
isLeaf: 表示这个区块是否所有元素都一样
Example:
Input: grid =
[[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
Output:
[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Explanation: All values in the grid are not the same. We divide the grid into
four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where
each has the same value.
Explanation is shown in the photo below:
https://assets.leetcode.com/uploads/2020/02/12/e2mat.png
思路:
1.四元树是一个很特别的资料结构,如果矩阵的(x1,y1)到(x2,y2)区域的所有元素
都是0或1的话这个节点就是一个叶节点,可以用一个节点来表示,如果不是的话
,我们会将这个区域平均切成四个等分,再继续判断他是否所有元素都一样,
从上面的说明我们可以观察出来建构四元树是有递回关系的。
2.这边使用dfs来建构四元树,定义dfs(y1, x1, y2, x2)返回一个从(x1,y1)到(x2,y2)
区域所构建出来的四元树,可以分成两种情况:
(1)这个区域的所有元素都相同:直接返回一个叶节点,节点的值就是这个元素。
(2)这个区域存在某个元素不相同:将当前区域均分成四等分往四个区块继续递回。
3.递回到底之后就可以构建出四元树了。
Java Code:
作者: SuiseiLeda (星街雷达)   2023-02-27 16:16:00
四元树是啥
作者: Firstshadow (IamCatづミ'_'ミづ)   2023-02-27 16:16:00
大师
作者: DDFox (冒险者兼清洁工)   2023-02-27 16:16:00
大师
作者: pandix (面包屌)   2023-02-27 16:31:00
大师
作者: idiont (supertroller)   2023-02-27 16:41:00
我好像以前在其他OJ写过一模一样的题目
作者: pandix (面包屌)   2023-02-27 16:47:00
感觉先递回建子node再检查是不是全部元素都一样比较好
作者: Che31128 (justjoke)   2023-02-27 16:59:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com