码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode&Python] Problem 427. Construct Quad Tree

时间:2018-11-21 16:07:23      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:you   div   wing   att   about   none   example   技术分享   self   

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 valisLeaf 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:

  1. N is less than 1000 and guaranteened to be a power of 2.
  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

标签:you   div   wing   att   about   none   example   技术分享   self   

原文地址:https://www.cnblogs.com/chiyeung/p/9994156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!