427. 建立四叉树(2022-4-29)
题太长了,还请移步官网查看
链接:https://leetcode-cn.com/problems/construct-quad-tree
解题思路
本题看题比较费劲,建议直接看例子,理解的快一些。
很容易就想到了分治法,只是在实现上有些一筹莫展;实则约束索引即可达成分区。分区之后就是递归了,没什么难度。
参考这位大佬的写法,直接点醒了属于是。
var construct = function(grid,[x,y,n]=[0,0,grid.length]) {
// 相等 是叶子 就直接返回
if(_isLeaf(grid,x,y,n)){
return new Node(grid[x][y],true,null,null,null,null)
}
// 不相等 不是叶子 就分四份
const blocks = [[x,y,n/2],[x,y+n/2,n/2],[x+n/2,y,n/2],[x+n/2,y+n/2,n/2]]
return new Node(1,0,
construct(grid,blocks[0]),
construct(grid,blocks[1]),
construct(grid,blocks[2]),
construct(grid,blocks[3])
)
};
function _isLeaf(grid,x,y,n){
for(let i = x; i < x+n; i++){
for(let j = y; j < y+n; j++){
if(!grid[i][j] == grid[x][y]) return false
}
}
return true
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-quad-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。