[LeetCode&Python] Problem 427. Construct Quad Tree
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[LeetCode&Python] Problem 427. Construct Quad Tree,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1887字,纯文字阅读大概需要3分钟。
内容图文
![[LeetCode&Python] Problem 427. Construct Quad Tree](/upload/InfoBanner/zyjiaocheng/847/57c6516bdff546ec887566343e5a8b0f.jpg)
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:
Given the 8 x 8
grid below, we want to construct the corresponding quad tree:
It can be divided according to the definition above:
The corresponding quad tree should be as following, where each node is represented as a (isLeaf, val)
pair.
For the non-leaf nodes, val
can be arbitrary, so it is represented as *
.
Note:
N
is less than1000
and guaranteened to be a power of 2.- If you want to know more about the quad tree, you can refer to its wiki.
""" # Definition for a QuadTree node. class Node(object): def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight """ class Solution(object): def construct(self, grid): """ :type grid: List[List[int]] :rtype: Node """ if not grid: return None if self.isLeaf(grid): return Node(grid[0][0]==1,True,None,None,None,None) N=len(grid) return Node('*',False,self.construct([rows[:N/2] for rows in grid[:N/2]]),self.construct([rows[N/2:] for rows in grid[:N/2]]),self.construct([rows[:N/2] for rows in grid[N/2:]]),self.construct([rows[N/2:] for rows in grid[N/2:]])) def isLeaf(self,grid): if not grid: return True a=set() for i in grid: for j in range(len(grid)): a.add(i[j]) if len(a)>1: return False return True
内容总结
以上是互联网集市为您收集整理的[LeetCode&Python] Problem 427. Construct Quad Tree全部内容,希望文章能够帮你解决[LeetCode&Python] Problem 427. Construct Quad Tree所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。